Flutter学习 — 使用不同类型的子项创建列表
2023-09-14 09:04:26 时间
效果图:
代码+注释:
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);
}
喜欢记得点个赞哟,我是王睿,很高兴认识大家!
更多原理请参考谷歌官网:使用不同类型的子项创建列表
相关文章
- Java实现 LeetCode 599 两个列表的最小索引总和(使用hash提高效率)
- 实例讲解-单向列表的实现(1)
- Flutter ReorderableListView 可拖拽的列表
- Flutter NotificationListener 监听列表的滚动
- 前端学习 -- Css -- 有序列表和无序列表
- 好友聊天消息列表本地数据库封装
- 将元素为多个列表的列表元素进行转置、去重处理
- 我是如何做列表页的
- Flutter学习 — 使用长列表
- flutter 简单的网格列表
- flutter在导航栏处实现对两个列表的点击事件
- Flutter 页面滑动嵌套列表不能滑动
- Flutter 官网的列表点击收藏
- Python编程语言学习:将多个列表数据保存为dataframe格式数据并按照指定列进行降序排序之详细攻略
- QT 播放器之列表[通俗易懂]
- littlevgl之list 列表控件
- 跳跃列表(Skip List)与其在Redis中的实现详解
- 【SQL开发实战技巧】系列(十二):三问(如何对字符串字母去重后按字母顺序排列字符串?如何识别哪些字符串中包含数字?如何将分隔数据转换为多值IN列表?)
- Python将列表元素按指定个数分组小技巧
- Flutter ListView 基础列表组件、水平 列表组件、动态列表图标组件
- 【redis源码学习】紧凑列表 listpack,t_hash的御用底层结构