【问题标题】:How to create a widget automatically multiple times with different data being passes from an array?如何使用从数组传递的不同数据多次自动创建小部件?
【发布时间】:2020-11-01 06:48:56
【问题描述】:

例如,

让有一个 Widget 叫 TestButton :

class TestButton extends StatelessWidget {
  final Function x;
  final String text;
  TestButton(this.x,this.text);
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      onPressed: x,
      child: Text(
       text,
       style: TextStyle(fontSize: 28),
      ),
   );
 }
}

而不是写:

TestButton(increaseCounter,'text1');
TestButton(increaseCounter,'text2');
TestButton(increaseCounter,'text3');

创建 3 个带有文本的按钮:text1、text2、text3

如何让 Flutter 从数组中读取数据,创建与数组中的元素一样多的按钮,并将每个元素的数据作为第二个位置参数传递。

var a=['test1','test2','test3'];//array example

【问题讨论】:

  • 上述程序的示例代码 sn-p 会有所帮助。

标签: flutter dart


【解决方案1】:

您应该使用ListView.builder。像这样:

ListView.builder(
        shrinkWrap: true,
        physics: ScrollPhysics(),
        itemCount: a.length,
        itemBuilder: (context,index){
          return TestButton(increaseCounter,a[index]);
        },

      )

【讨论】:

    【解决方案2】:

    试试这个

    Column(
    children:[
         for(int i=0;i<a.length;i++)
         TestButton(increaseCounter,a[i])
        ],
     )
    

    或者

    Column (
    children: a.map((txt)=>TestButton(increaseCounter,txt)).toList()
    )
    

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 1970-01-01
      • 2017-05-24
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多