效果图:
代码+注释:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp(
// List.generate构造函数 —— 生成拥有1000个字符串的列表
items: new List<ListItem>.generate(
1000,
(i) => i % 6 == 0 //根据规律: 每一个标题后面会跟着五条内容
? new HeadingItem("Heading $i") //标题类型
: new MessageItem("Sender $i", "Message body $i"), //内容类型
),
));
}
class MyApp extends StatelessWidget {
final List<ListItem> items;
MyApp({Key key, @required this.items}) : super(key: key);
@override
Widget build(BuildContext context) {
final title = 'Mixed List';
return new MaterialApp(
title: title,
home: new Scaffold(
appBar: new AppBar(
title: new Text(title),
),
body: new ListView.builder(
// Let the ListView know how many items it needs to build
// 让ListView知道需要构建多少个项目
itemCount: items.length,
// Provide a builder function. This is where the magic happens! We'll
// 提供构建器功能。 这就是魔术发生的地方! 好
// convert each item into a Widget based on the type of item it is.
// 根据项目类型将每个项目转换为Widget。
itemBuilder: (context, index) {
final item = items[index]; //得到具体的items
if (item is HeadingItem) { //是否为标题类型
return new ListTile(
title: new Text(
item.heading,
style: Theme.of(context).textTheme.headline,
),
);
} else if (item is MessageItem) { //是否为内容类型
return new ListTile(
title: new Text(item.sender),
subtitle: new Text(item.body),
);
}
},
),
),
);
}
}
// The base class for the different types of items the List can contain
// 列表可以包含的不同类型的项目的基类
abstract class ListItem {}
// A ListItem that contains data to display a heading
// 一个ListItem,其中包含显示标题的数据
class HeadingItem implements ListItem {
final String heading;
HeadingItem(this.heading);
}
// A ListItem that contains data to display a message
// 一个ListItem包含显示消息的数据
class MessageItem implements ListItem {
final String sender;
final String body;
MessageItem(this.sender, this.body);
}
喜欢记得点个赞哟,我是王睿,很高兴认识大家!
更多原理请参考谷歌官网:使用不同类型的子项创建列表