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

news2024/10/7 16:26:33

目标: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);

  @override
  Widget buildSubtitle(BuildContext context) {
    // 创建主标题
    return Text(
      title,
      style: Theme.of(context).textTheme.headlineSmall,
    );
  }

  @override
  Widget buildTitle(BuildContext context) {
    return const SizedBox.shrink();
  }
}

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


/**
 * 含有主标题和副标题的列表项
 */
class MessageItem implements ListItem {
  final String title;
  final String message;

  const MessageItem(this.title, this.message);

  @override
  Widget buildSubtitle(BuildContext context) {
    // 创建主标题
    return Text(
      title,
      style: Theme.of(context).textTheme.headlineSmall,
    );
  }

  @override
  Widget 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.
  @override
  Widget 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;

  @override
  State<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++;
    });
  }

  @override
  Widget 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) {
          // 返回列表项的ListTile
          return 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) {
          // 返回列表项的ListTile
          return ListTile(
            // 主标题(通过ListItem创建主标题)
            title: widget.items[index].buildTitle(context),
            subtitle: widget.items[index].buildSubtitle(context),
          );
        },
      ).build(context),

以下是展现效果。

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

韩顺平Java | C25 JDBC和连接池(上)

概述 JDBC概述&#xff1a;JDBC为访问不同数据库提供统一接口&#xff0c;为使用者屏蔽细节问题。Java程序员使用JDBC可以连接任何提供了JDBC驱动程序的数据库系统&#xff0c;从而完成对数据库的各种操作。 // 模拟代码 //JdbcInterface.java --Java规定的JDBC接口(方法) p…

Linux-文件系统理解(磁盘的物理与逻辑结构、什么是inode、OS如何管理磁盘)

一、磁盘 磁盘的物理结构 磁盘的本质是一个机械设备&#xff0c;可以存储大量的二进制信息&#xff0c;是实现数据存储的基础硬件设施&#xff0c;磁盘的盘片类似于光盘&#xff0c;不过盘片的两面都是可读可写可擦除的&#xff0c;每个盘面都有一个磁头&#xff0c;马达可以使…

keil无法查看外设寄存器(生成SFR文件)

1.前言 自从更新了keil&#xff0c;用的是越来越不顺手了&#xff0c;一会是cannot evaluate&#xff0c;一会是与强制与cubemx强制联系了&#xff0c;这次也是的&#xff08;地铁&#xff0c;老人&#xff0c;手机&#xff09;折腾了一下总是搞好了&#xff08;网上的解法只能…

安卓刷机fastboot分段传输

win10 fastboot 无法识别&#xff0c;驱动下载地址GitHub - xushuan/google_latest_usb_driver_windows 把inf文件更新到设备管理器驱动更新即可 问题 archive does not contain super_empty.img Sending vbmeta_a (4 KB) OKAY [ 0.117s] Writing …

Open CASCADE学习|实现Extrude功能

首先定义了一些基本的几何元素&#xff0c;如线、圆和平面&#xff0c;然后使用makeExtrudebydir函数来对一个面进行挤出操作。下面是详细过程&#xff1a; 定义Extrude函数&#xff1a;makeExtrudebydir函数接受一个TopoDS_Shape对象和一个gp_Vec对象作为参数。TopoDS_Shape是…

【vs2019】window10环境变量设置

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

【Unity添加远程桌面】使用Unity账号远程控制N台电脑

设置地址&#xff1a; URDP终极远程桌面&#xff1b;功能强大&#xff0c;足以让开发人员、设计师、建筑师、工程师等等随时随地完成工作或协助别人https://cloud-desktop.u3dcloud.cn/在网站登录自己的Unity 账号上去 下载安装被控端安装 保持登录 3.代码添加当前主机 "…

初探vercel托管项目

文章目录 第一步、注册与登录第二步、本地部署 在个人网站部署的助手vercel&#xff0c;支持 Github部署&#xff0c;只需简单操作&#xff0c;即可发布&#xff0c;方便快捷&#xff01; 第一步、注册与登录 进入vercel【官网】&#xff0c;在右上角 login on&#xff0c;可登…

【小迪安全2023】第23天:WEB攻防-Python考点CTF与CMS-SSTI模版注入PYC反编译

&#x1f36c; 博主介绍&#x1f468;‍&#x1f393; 博主介绍&#xff1a;大家好&#xff0c;我是 hacker-routing &#xff0c;很高兴认识大家~ ✨主攻领域&#xff1a;【渗透领域】【应急响应】 【Java、PHP】 【VulnHub靶场复现】【面试分析】 &#x1f389;点赞➕评论➕收…

Linux 文件页反向映射

0. 引言 操作系统中与匿名页相对的是文件页&#xff0c;文件页的反向映射对比匿名页的反向映射更为简单。如果还不清楚匿名页反向映射逻辑的&#xff0c;请移步 匿名页反向映射 1. 文件页反向映射数据结构 struct file&#xff1a; 用户进程每open()一次文件&#xff0c;则会生…

微服务相关

1. 微服务主要七个模块 中央管理平台&#xff1a;生产者、消费者注册&#xff0c;服务发现&#xff0c;服务治理&#xff0c;调用关系生产者消费者权限管理流量管理自定义传输协议序列化反序列化 2. 中央管理平台 生产者A在中央管理平台注册后&#xff0c;中央管理平台会给他…

BLIP 算法阅读记录---一个许多多模态大语言模型的基本组件

论文地址&#xff1a;&#x1f608; 目录 一、环境配置以及数据集准备 数据集准备 数据集格式展示 环境配置&#xff0c;按照官网所述即可 二、一些调整 vit_base的预训练模型 远程debug的设置 Tokenizer初始化失败 读入网络图片的调整 三、训练过程 Image Encoder …

Kylin IPv4 setting config

Kylin IPv4 setting-CSDN博客 上次配置完重启又没了&#xff0c;永久需要修改配置文件 /etc/sysconfig/network-scripts ifcfg-ens33

langchain-chatchat指定一个或多个文件回答,不允许回答内容有其他文件内容,即屏蔽其他文件内容

1.找到langchain-chatchat中的knowledge_base_chat.py 2.knowledge_base_chat.py的api内容加上一个flie_name参数&#xff0c;即传过来你需要指定一个文件名称&#xff0c;或多个文件名称&#xff0c;同时也可以不指定&#xff0c;加上以下代码&#xff1a; flie_name: List …

腾讯云优惠券详细介绍及领券步骤详解

随着云计算技术的不断发展和普及&#xff0c;越来越多的企业和个人开始选择使用云服务来满足自身的需求。腾讯云作为国内领先的云服务提供商&#xff0c;以其稳定、高效、安全的服务赢得了广大用户的信赖。为了回馈广大用户&#xff0c;腾讯云经常推出各种优惠活动&#xff0c;…

linux下安装nacos2.2.0

1、获取下载地址并下载 1.1、打开nacos官网 1.2、找到对应版本&#xff0c;点进去 ## 1.3、复制地址 1.4下载 # 进入要安装的目录&#xff0c;cd /usr/local/src # 执行wget https://github.com/alibaba/nacos/releases/download/2.2.0/nacos-server-2.2.0.tar.gz2、 安装…

深入理解计算机网络分层结构

一、 为什么要分层&#xff1f; 计算机网络分层的主要目的是将复杂的网络通信过程分解为多个相互独立的层次&#xff0c;每个层次负责特定的功能。这样做有以下几个好处&#xff1a; 模块化设计&#xff1a;每个层次都有清晰定义的功能和接口&#xff0c;使得网络系统更易于设…

放弃powershell? 启动 sqlps!免杀| 红队攻防

0x00 前言 sql server 默认安装后&#xff0c;会发现有一个 sqlps.exe&#xff1a; 此文件本身自带微软签名&#xff1a; sqlps的功能&#xff0c;竟然是&#xff01;启动 powershell&#xff1f;&#xff1f;&#xff1f; 而且由于此文件无依赖&#xff0c;因此可以单独取出在…

刷题之Leetcode206题(超级详细)

206.反转链表 力扣题目链接(opens new window)https://leetcode.cn/problems/reverse-linked-list/ 题意&#xff1a;反转一个单链表。 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL 思路 如果再定义一个新的链表&#xff0…

18 进程替换

目录 1.什么是进程替换 2.替换原理 3.替换函数 4.函数解释 5.具体应用 6.makefile构建多个文件 7.运行自己程序 8.运行其他语言程序 9.简易shell 什么是进程替换 fork之后的父子程序共享代码&#xff0c;如果子进程想执行一个全新的程序。就用进程替换来完成这个功能&#x…