はじめに
FlutterのListViewを勉強しシンプルなチャット画面を作成しました。
本記事では備忘録も兼ねてまとめたものになります。
環境
- Flutter 3.22.1
ListView
スクロール可能なリスト一覧を作成できるwidget。
ListView.builder
多数のデータを一覧表示させる際に使用を推奨されるもの。
「ListView.builder」で作成すると、実際に表示されている子要素のみビルダーが呼び出されるため随時読み込みなど、多数(または無限)のリストを表示する場合に利用する作成方法です。
引用 ListView 2:https://flutter.ctrnost.com/basic/layout/listview/
ソース
アプリのホーム画面としてChatScreen
Widgetを作成しています。
ListView
を使用して20個のチャットメッセージを生成し、インデックスが偶数のものは自分が送信したメッセージ、奇数のものは相手のメッセージを想定しています。
main.dart
import 'package:flutter/material.dart';
import 'chat.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: ChatScreen(),
);
}
}
class ChatScreen extends StatelessWidget {
const ChatScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Chat Example'),
),
body: ListView.builder(
itemCount: 20, // リストビューの要素数を設定
itemBuilder: (context, index) {
return ChatSample(
message: '要素 $index', // メッセージの内容を生成 例:要素 1、要素 2・・・
isMe: index % 2 == 0, // 偶数インデックスは自分が送ったメッセージと仮定
);
},
),
);
}
}
下記のChatSample
Widgetではメッセージボックスを描画しています。
自分のメッセージかどうかを示すisMe
のフラグに応じて右 or 左寄せで、背景色が異なるメッセージボックスを描画してます。
chat.dart
import 'package:flutter/material.dart';
class ChatSample extends StatelessWidget {
final String message;
final bool isMe; // フラグ
const ChatSample({required this.message, required this.isMe, super.key});
@override
Widget build(BuildContext context) {
return Align(
alignment: isMe
? Alignment.centerRight
: Alignment.centerLeft, // 自分のメッセージの場合は右寄せ、それ以外は左寄せ想定
child: Container(
margin: const EdgeInsets.symmetric(
vertical: 5.0, horizontal: 10.0),
padding: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: isMe
? Colors.greenAccent
: Colors.grey[300], // 自分のメッセージは緑色で表示
borderRadius: BorderRadius.circular(12.0),
),
child: Text(
message,
style: const TextStyle(fontSize: 16.0),
),
),
);
}
}
実行結果
デバッグして確認すると、次の画像のように相手とやりとりしている事を想定した画面を描画できました。
参考