ListViewで同じフォーマットのものを並べる練習です。
SNSアプリや情報メディアを作る時に便利そう
main.dart
import 'package:flutter/material.dart';
// ツイート
class Tweet {
// ユーザーの名前
final String userName;
// アイコン画像
final String iconUrl;
// 文章メッセージ
final String text;
// 送信日時
final String createdAt;
// コンストラクタ
Tweet(this.userName, this.iconUrl, this.text, this.createdAt);
}
// 適当なモデル
final models = [
Tweet('ルフィ', 'icon1.png', '海賊王におれはなる!', '2022/1/1'),
Tweet('バルトロメオ', 'icon1.png', 'この子分盃!勝手に頂戴いたしますだべ!', '2022/3/1'),
];
// モデル => ウィジェット に変換する。ここのmodelは引数で仮のキーワード
Widget modelToWidget(Tweet model) {
// ユーザーアイコン
final icon = Container(
margin: const EdgeInsets.all(20),
width: 60,
height: 60,
// 画像を丸くする
child: ClipRRect(
borderRadius: BorderRadius.circular(30.0),
child: Image.asset('assets/images/${model.iconUrl}'),
),
);
// 名前と時間
final metaText = Container(
padding: const EdgeInsets.all(6),
height: 40,
alignment: Alignment.centerLeft,
child: Text(
'${model.userName} ${model.createdAt}',
style: const TextStyle(color: Colors.grey),
),
);
// 本文
final text = Container(
padding: const EdgeInsets.all(8),
alignment: Alignment.centerLeft,
child: Text(
model.text,
style: const TextStyle(fontWeight: FontWeight.bold),
),
);
// 部品を並べる
return Container(
padding: const EdgeInsets.all(1),
decoration: BoxDecoration(
// 全体を青い枠線で囲む
border: Border.all(color: Colors.blue),
color: Colors.white,
),
width: double.infinity,
// 高さ
height: 120,
child: Row(
children: [
// アイコン
icon,
Expanded(
child: Column(
children: [
// 名前と時間
metaText,
// 本文
text,
],
),
),
],
),
);
}
// メイン関数
void main() {
// ツイートのリスト
final list = ListView.builder(
itemCount: models.length,
itemBuilder: (c, i) => modelToWidget(models[i]),
//上の仮キーワードmodelsに作ったmodelsを具体的に代入している
);
final con = Center(
child: SizedBox(
height: 400,
child: list,
),
);
// 画面
final sca = Scaffold(
backgroundColor: Colors.grey,
body: con,
);
// アプリ
final app = MaterialApp(home: sca);
// アプリを動かす
runApp(app);
}