Flutter学习笔记06-ListView动态列表

学习视频链接:https://www.bilibili.com/video/BV1S4411E7LY/?p=25&spm_id_from=pageDriver&vd_source=cee744cae4ead27f8193fc7904647073

视频学习笔记:
1.生成一个动态列表

import 'package:first_flutter_app/myIcon.dart';
import 'package:flutter/material.dart';

void main() {
  //const : 多个相同的实例共享存储空间
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.blue),
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Flutter ICON"),
        ),
        body: const MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  List<Widget> _initData() {
    List<Widget> list = [];
    for (int i = 0; i < 20; i++) {
      list.add(ListTile(
        title: Text("我是第$i个元素"),
      ));
    }
    return list;
  }

  
  Widget build(BuildContext context) {
    return ListView(
      children: _initData(),
    );
  }
}

显示效果:
在这里插入图片描述
代码分析:
这是我们第一次编写dart函数

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  List<Widget> _initData() {
    List<Widget> list = [];
    for (int i = 0; i < 20; i++) {
      list.add(ListTile(
        title: Text("我是第$i个元素"),
      ));
    }
    return list;
  }

  
  Widget build(BuildContext context) {
    return ListView(
      children: _initData(),
    );
  }
}

在MyHomePage类中,我们首先在build方法的返回值返回一个Listview,但这个Listview的children不再是一个具体的List,而是调用了_initData()方法,当然我们会获取它的返回值,并且它的返回值类型也是List。

List<Widget> _initData() {
    List<Widget> list = [];
    for (int i = 0; i < 20; i++) {
      list.add(ListTile(
        title: Text("我是第$i个元素"),
      ));
    }
    return list;
  }

分析:
1.dart方法名前有“_”代表方法是私有的
2.初始化List,“=”需要写方括号“[]”

2.加载其他文件的数据
先创建一个存放数据的文件listData.dart

var listData = [
  {"title": "1", "content": "this is 1 item"},
  {"title": "2", "content": "this is 2 item"},
  {"title": "3", "content": "this is 3 item"},
  {"title": "4", "content": "this is 4 item"},
  {"title": "5", "content": "this is 5 item"},
  {"title": "6", "content": "this is 6 item"},
  {"title": "7", "content": "this is 7 item"},
  {"title": "8", "content": "this is 8 item"},
  {"title": "9", "content": "this is 9 item"},
  {"title": "10", "content": "this is 10 item"},
  {"title": "11", "content": "this is 11 item"},
  {"title": "12", "content": "this is 12 item"},
  {"title": "13", "content": "this is 13 item"},
];

在main.dart中import

import 'package:first_flutter_app/listData.dart';

使用

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  List<Widget> _initData() {
    List<Widget> tempList = [];
    for (var i = 0; i < listData.length; i++) {
      tempList.add(ListTile(
        title: Text("我是第${listData[i]["title"]}个元素"),
        subtitle: Text("${listData[i]["content"]}"),
      ));
    }
    return tempList;
  }

  
  Widget build(BuildContext context) {
    return ListView(
      children: _initData(),
    );
  }
}

显示效果
在这里插入图片描述

还有另一种遍历元素的写法

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  List<Widget> _initData() {
    var tempList = listData.map((value) {
      return ListTile(
        title: Text("这是第${value["title"]}个元素"),
        subtitle: Text("${value["content"]}"),
      );
    });
    return tempList.toList();
  }

  
  Widget build(BuildContext context) {
    return ListView(
      children: _initData(),
    );
  }
}

map方法:

/// Returns a new lazy [Iterable] with elements that are created by
  /// calling `f` on each element of this `Iterable` in iteration order.
  ///
  /// This method returns a view of the mapped elements. As long as the
  /// returned [Iterable] is not iterated over, the supplied function [f] will
  /// not be invoked. The transformed elements will not be cached. Iterating
  /// multiple times over the returned [Iterable] will invoke the supplied
  /// function [f] multiple times on the same element.
  ///
  /// Methods on the returned iterable are allowed to omit calling `f`
  /// on any element where the result isn't needed.
  /// For example, [elementAt] may call `f` only once.
  Iterable<T> map<T>(T f(E e)) => MappedIterable<E, T>(this, f);

tolist方法

/// Creates a [List] containing the elements of this [Iterable].
  ///
  /// The elements are in iteration order.
  /// The list is fixed-length if [growable] is false.
  List<E> toList({bool growable = true}) {
    return List<E>.of(this, growable: growable);
  }

2.使用ListView的builder构建列表

class MyHomePage extends StatelessWidget {
  final List<String> list = [];

  MyHomePage({Key? key}) : super(key: key) {
    for (var i = 0; i < 20; i++) {
      list.add("这是第$i条数据");
    }
  }

  
  Widget build(BuildContext context) {
    return ListView.builder(itemBuilder: (context, index) {
      return ListTile(
        title: Text("${list[index]}"),
      );
    });
  }
}

会报错
在这里插入图片描述
需要在Builder添加属性itemCount

ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index) {
      return ListTile(
        title: Text("${list[index]}"),
      );
    });

就正常了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值