Flutter学习 — 使用不同类型的子项创建列表

效果图:

在这里插入图片描述

代码+注释:

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);
}

喜欢记得点个赞哟,我是王睿,很高兴认识大家!

更多原理请参考谷歌官网:使用不同类型的子项创建列表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王睿丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值