Flutter第八弹 构建拥有不同项的列表

目标:1)项目中,数据源可能涉及不同的模版,显示不同类型的子项,类似RecycleView的itemType, 有多种类型,列表怎么显示?

2)不同的数据源构建列表

一、创建不同的数据源

采用类似RecyclerView的思想,不同的数据源,对应不同的子项Widget进行展现;

因为需要列表项统一展现,因此最好抽取一个子项的公共基类,进行统一处理。

1.1 创建数据源基类

抽取统一基类,列表项显示主标题和副标题。

  • 一种子项只显示主标题;
  • 另一类子项显示主标题和副标题
/// The base class for the different types of items the list can contain.
abstract class ListItem {/// The title line to show in a list item.Widget buildTitle(BuildContext context);/// The subtitle line, if any, to show in a list item.Widget buildSubtitle(BuildContext context);
}

1.2 创建不同数据源

只有主标题的数据源


/*** 为什么使用implements,而不是extends?* 因为是ListItem的实现类,已经实现ListItem的抽象方法了。* 如果是extends, 意味着HeadingItem不需要实现抽象方法,自身仍然作为抽象类使用*/
class HeadingItem implements ListItem {final String title;/*** 为什么需要const修饰符?*/const HeadingItem(this.title);@overrideWidget buildSubtitle(BuildContext context) {// 创建主标题return Text(title,style: Theme.of(context).textTheme.headlineSmall,);}@overrideWidget buildTitle(BuildContext context) {return const SizedBox.shrink();}
}

包含主标题和副标题的数据源


/*** 含有主标题和副标题的列表项*/
class MessageItem implements ListItem {final String title;final String message;const MessageItem(this.title, this.message);@overrideWidget buildSubtitle(BuildContext context) {// 创建主标题return Text(title,style: Theme.of(context).textTheme.headlineSmall,);}@overrideWidget buildTitle(BuildContext context) {// 创建副标题return Text(message,style: Theme.of(context).textTheme.headlineSmall,);}
}

二、创建不同数据源的列表

我们知道ListView的子项是ListTile,因此我们需要将数据源填充到ListTile中。

void main() {runApp(MyApp(),);
}class MyApp extends StatelessWidget {const MyApp({super.key});// This widget is the root of your application.@overrideWidget build(BuildContext context) {return MaterialApp(title: 'Flutter Demo',theme: ThemeData(// This is the theme of your application.//// TRY THIS: Try running your application with "flutter run". You'll see// the application has a purple toolbar. Then, without quitting the app,// try changing the seedColor in the colorScheme below to Colors.green// and then invoke "hot reload" (save your changes or press the "hot// reload" button in a Flutter-supported IDE, or press "r" if you used// the command line to start the app).//// Notice that the counter didn't reset back to zero; the application// state is not lost during the reload. To reset the state, use hot// restart instead.//// This works for code too, not just values: Most code changes can be// tested with just a hot reload.colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),useMaterial3: true,),home: MyHomePage(title: 'Flutter Demo Home Page'),);}
}@immutable
class MyHomePage extends StatefulWidget {List<ListItem> items = List<ListItem>.generate(1000,(i) => i % 6 == 0? HeadingItem('Heading $i'): MessageItem('Sender $i', 'Message body $i'),);MyHomePage({super.key, required this.title});// This widget is the home page of your application. It is stateful, meaning// that it has a State object (defined below) that contains fields that affect// how it looks.// This class is the configuration for the state. It holds the values (in this// case the title) provided by the parent (in this case the App widget) and// used by the build method of the State. Fields in a Widget subclass are// always marked "final".final String title;@overrideState<MyHomePage> createState() => _MyHomePageState();
}class _MyHomePageState extends State<MyHomePage> {int _counter = 0;void _incrementCounter() {setState(() {// This call to setState tells the Flutter framework that something has// changed in this State, which causes it to rerun the build method below// so that the display can reflect the updated values. If we changed// _counter without calling setState(), then the build method would not be// called again, and so nothing would appear to happen._counter++;});}@overrideWidget build(BuildContext context) {// This method is rerun every time setState is called, for instance as done// by the _incrementCounter method above.//// The Flutter framework has been optimized to make rerunning build methods// fast, so that you can just rebuild anything that needs updating rather// than having to individually change instances of widgets.return Scaffold(appBar: AppBar(// TRY THIS: Try changing the color here to a specific color (to// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar// change color while the other colors stay the same.backgroundColor: Theme.of(context).colorScheme.inversePrimary,// Here we take the value from the MyHomePage object that was created by// the App.build method, and use it to set our appbar title.title: Text(widget.title),),// 根据数据源创建不同项的列表body: ListView.builder(// 列表项个数itemCount: widget.items.length,// 列表项构建器itemBuilder: (context, index) {// 返回列表项的ListTilereturn ListTile(// 主标题(通过ListItem创建主标题)title: widget.items[index].buildTitle(context),subtitle: widget.items[index].buildSubtitle(context),);},).build(context),floatingActionButton: FloatingActionButton(onPressed: _incrementCounter,tooltip: 'Increment',child: const Icon(Icons.add),), // This trailing comma makes auto-formatting nicer for build methods.);

创建List Tile的时候,采用数据源ListItem进行填充,因为数据源有共同的基类,因此构建ListTile的时候就很方便。

      // 根据数据源创建不同项的列表body: ListView.builder(// 列表项个数itemCount: widget.items.length,// 列表项构建器itemBuilder: (context, index) {// 返回列表项的ListTilereturn ListTile(// 主标题(通过ListItem创建主标题)title: widget.items[index].buildTitle(context),subtitle: widget.items[index].buildSubtitle(context),);},).build(context),

以下是展现效果。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/618432.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++ | Leetcode C++题解之第27题移除元素

题目&#xff1a; 题解&#xff1a; class Solution { public:int removeElement(vector<int>& nums, int val) {int left 0, right nums.size();while (left < right) {if (nums[left] val) {nums[left] nums[right - 1];right--;} else {left;}}return lef…

minikube环境搭建

&#x1f4d5;作者简介&#xff1a; 过去日记&#xff0c;致力于Java、GoLang,Rust等多种编程语言&#xff0c;热爱技术&#xff0c;喜欢游戏的博主。 &#x1f4d8;相关专栏Rust初阶教程、go语言基础系列、spring教程等&#xff0c;大家有兴趣的可以看一看 &#x1f4d9;Jav…

深度学习学习日记4.14 数据增强 Unet网络部分

数据增强 transforms.Compose([&#xff1a;这表示创建一个转换组合&#xff0c;将多个数据转换操作串联在一起 transforms.RandomHorizontalFlip()&#xff1a;这个操作是随机水平翻转图像&#xff0c;以增加数据的多样性。它以一定的概率随机地水平翻转输入的图像。 transfo…

【云计算】云数据中心网络(二):弹性公网 IP

云数据中心网络&#xff08;二&#xff09;&#xff1a;弹性公网 IP 1.什么是弹性公网 IP2.弹性公网 IP 的类型2.1 多线 EIP2.2 任播 EIP2.3 单线静态 EIP2.4 精品 EIP2.5 识别不同类型的 IP 的地址 3.弹性公网 IP 功能3.1 自带公网 IP 地址上云3.2 尽力找回公网 IP 地址3.3 连…

发布 Chrome/Edge浏览器extension扩展到应用商店

Chrom Extension发布流程 创建和发布自定义 Chrome 应用和扩展程序&#xff1a;https://support.google.com/chrome/a/answer/2714278?hlzh-Hans 在 Chrome 应用商店中发布&#xff1a;https://developer.chrome.com/docs/webstore/publish?hlzh-cn 注册开发者帐号&#…

有真的副业推荐吗?

#有真的副业推荐吗# 我做副业项目的时候&#xff0c;认识了一位带娃宝妈&#xff0c;讲一下她空闲时间做副业赚钱的故事吧。在一个温馨的小家庭里&#xff0c;李婷是一位全职宝妈&#xff0c;她的主要任务是照顾和陪伴自己可爱的宝宝。然而&#xff0c;随着宝宝逐渐长大&#x…

【vs2019】window10环境变量设置

【vs2019】window10环境变量设置 【先赞后看养成习惯】求关注点赞收藏&#x1f60a; 安装VS2019时建议默认安装地址&#xff0c;最好不要改动&#xff0c;不然容易出问题 以下是安装完VS2019后环境变量的设置情况&#xff0c;C:\Program Files (x86)\Microsoft Visual Studi…

稀碎从零算法笔记Day48-LeetCode:三角形最小路径和

题型&#xff1a;DP、二维DP、矩阵 链接&#xff1a;120. 三角形最小路径和 - 力扣&#xff08;LeetCode&#xff09; 来源&#xff1a;LeetCode 题目描述 给定一个三角形 triangle &#xff0c;找出自顶向下的最小路径和。 每一步只能移动到下一行中相邻的结点上。相邻的…

L3 【哈工大_操作系统】操作系统启动

本节要点&#xff1a; 1、理解 OS 启动过程发生了什么&#xff0c;理解 OS 与 硬件 与 应用 之间的关系 2、本节讲解了 setup 模块 和 system 模块实现的功能 1、计算机上电时&#xff0c;操作系统在硬盘&#xff08;磁盘&#xff09;上&#xff0c;为了“取指执行”&#xff0…

44.HarmonyOS鸿蒙系统 App(ArkUI)栅格布局介绍

栅格布局是一种通用的辅助定位工具&#xff0c;对移动设备的界面设计有较好的借鉴作用。主要优势包括&#xff1a; 提供可循的规律&#xff1a;栅格布局可以为布局提供规律性的结构&#xff0c;解决多尺寸多设备的动态布局问题。通过将页面划分为等宽的列数和行数&#xff0c;…

扣子Coze插件教程:如何使用Coze IDE创建插件

&#x1f9d9;‍♂️ 诸位好&#xff0c;吾乃斜杠君&#xff0c;编程界之翘楚&#xff0c;代码之大师。算法如流水&#xff0c;逻辑如棋局。 &#x1f4dc; 吾之笔记&#xff0c;内含诸般技术之秘诀。吾欲以此笔记&#xff0c;传授编程之道&#xff0c;助汝解技术难题。 &#…

探索Sora:OpenAI的革新性视频生成技术

探索Sora&#xff1a;OpenAI的革新性视频生成技术 在数字时代的浪潮中&#xff0c;人工智能&#xff08;AI&#xff09;逐渐渗透到我们生活的方方面面&#xff0c;不断推动着科技与创意的边界。近日&#xff0c;OpenAI发布了一款名为Sora的新工具&#xff0c;它利用数据驱动的物…