【问题标题】:Rendering multiple/dynamic widgets based on a list in Flutter?基于 Flutter 中的列表渲染多个/动态小部件?
【发布时间】:2020-06-10 15:58:35
【问题描述】:

我正在尝试基于项目(条目)列表构建动态小部件(卡片、块、具有某些属性的容器)。尝试为此创建一个函数(我不需要为此创建一个单独的类吗?)。

  List entries = ['stock1', 'stock2', 'stock3'];

  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]}')),
          );
        });
  }

然后我尝试调用该函数并将我的主体添加到小部件列表中,以便它自动构建所有小部件(我不必手动一一创建它们)。

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: <Widget>[
          Container(
              height: 20.0,
              alignment: Alignment.center,
              padding: EdgeInsets.only(bottom: 8.0),
              color: Colors.lightBlue,
              child: Text('Hello. This is a Container')), //Container
          buildListView(),
        ],
      ),
    );
  }

我还读过某处你可以以某种方式使用.map() 方法,如果它与这里相关?

如何让它发挥作用?请分享有关此主题的解决方案/想法或有用的资源/链接。

【问题讨论】:

    标签: flutter dart flutter-widget


    【解决方案1】:

    是的,你可以做到:

    Column(
       children: [
            for(final entry in entries)
              Container(
                height: 50,
                color: Colors.lightBlue,
                child: Center(child: Text(entry)),
              ),
            ],
    ),
    

    或者如果你想使用map,你需要在最后添加toList():

    entries.map((entry) => Container(
                height: 50,
                color: Colors.lightBlue,
                child: Center(child: Text(entry)),
              ),
              ).toList(),
    

    Read article on this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-26
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 2018-12-21
      • 2021-03-13
      • 2017-02-03
      相关资源
      最近更新 更多