Flutter学习笔记05:动态列表

构造动态列表的方式:

定义全局列表:

List l = [
  {
    'name': '雪',
    'avatar': 'https://avatars.githubusercontent.com/u/42002296?v=4',
  },
  {
    'name': 'xue',
    'avatar': 'https://avatars.githubusercontent.com/u/42002296?v=4',
  },
  {
    'name': '雪碧',
    'avatar': 'https://avatars.githubusercontent.com/u/42002296?v=4',
  },
  {
    'name': '雪花',
    'avatar': 'https://avatars.githubusercontent.com/u/42002296?v=4',
  }
];

1:通过builder函数

home: Scaffold(
            appBar: AppBar(
              title: Text(title),
              backgroundColor: Colors.lightBlue,
            ),
            body: ListView.builder(
              itemCount: l.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  leading: CircleAvatar(
                    backgroundImage: NetworkImage(l[index]['avatar']),
                  ),
                  title: Text(l[index]['name']),
                  onTap: () {
                    if (kDebugMode) {
                      print('点击了${l[index]['name']}');
                    }
                  },
                );
              },
            ))

2:通过自定义构造函数

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  List<Widget> _initListData() {
    List<Widget> list = [];
    for (var i = 0; i < l.length; i++) {
      list.add(ListTile(
        leading: CircleAvatar(
          backgroundImage: NetworkImage(l[i]['avatar']),
        ),
        title: Text(l[i]['name']),
        onTap: () {
          if (kDebugMode) {
            print('点击了${l[i]['name']}');
          }
        },
      ));
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    var title = 'Test App';
    return MaterialApp(
        title: title,
        home: Scaffold(
            appBar: AppBar(
              title: Text(title),
              backgroundColor: Colors.lightBlue,
            ),
            body: ListView(
              children: _initListData(),
            )));
  }
}

效果:

你刚刚浪费了人生中宝贵的几分钟。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇