【问题标题】:Building dynamic widgets in Flutter在 Flutter 中构建动态小部件
【发布时间】:2020-06-09 22:30:47
【问题描述】:

您能否帮助我们如何构建小部件的动态列表,而不是手动构建卡片(容器或小部件)?使用 ListView.build 还是其他方法?最好的方法是什么?

我花了一天时间尝试和研究。我没有添加 3 张卡片(或具有多个属性的其他对象),而是尝试构建一个方法或函数,该方法或函数将根据列表(和长度)构建每个卡片(对象),然后将所有自动构建的卡片插入[]。

我一直在尝试实现它,但是当我将它添加到 [] 时出现了一些问题,可能是因为类型错误,或者我做错了什么?并且不确定这是否是最好的(如果完全正确的话)?

List entries = ['one', 'two', 'three3'];

Widget buildListView() {
  return ListView.builder(
      padding: EdgeInsets.all(8),
      itemCount: entries.length,
      itemBuilder: (BuildContext context, int index) {
        return new Container(
          height: 50,
          color: Colors.lightBlue,
          child: Center(child: Text('Entry ${entries[index]}')),
        );
      });
}

【问题讨论】:

  • 您是否尝试直接创建小部件列表并将其作为一个整体传递给 listview 构建器?

标签: flutter flutter-widget


【解决方案1】:

给你。

 ///construct the list of dynamic widgets as per your requirement.
 final listWidgets = [Text("one"), Text("two"), Text("three")];


 ///pass the widgets to the listview builder.
 return ListView.builder(
    padding: EdgeInsets.all(8),
    itemCount: listWidgets.length,
    itemBuilder: (BuildContext context, int index) {
      return new Container(
        height: 50,
        color: Colors.lightBlue,
        child: listWidgets[index],
      );
    });
    });

【讨论】:

    猜你喜欢
    • 2017-10-19
    • 2021-09-15
    • 2020-11-11
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2018-11-27
    • 2020-01-07
    • 1970-01-01
    相关资源
    最近更新 更多