在Flutter中动态生成小部件

时间:2019-03-18 07:38:09

标签: flutter

我正在尝试根据特定条件动态生成一组小部件。在这种情况下,我试图生成RadioTiles列表

这就是我尝试生成的方式

  List _listings = new List();

  Widget _getListings() {
    // TODO this will accept json objects in order to display the data
    List listings = new List();
    int i = 0;
    for (i = 0; i < 5; i++) {
      listings.add(
        new RadioListTile<SingingCharacter>(
          title: const Text('Lafayette'),
          value: SingingCharacter.lafayette,
          groupValue: _character,
          onChanged: (SingingCharacter value) {
            setState(() {
              _character = value;
            });
          },
        ),
      );
    }
//     return listings;
  }

并且我试图在这样的有状态小部件中显示此内容:

 return new SafeArea(
        child: Column(children: <Widget>[
      new Padding(
        padding: const EdgeInsets.all(20.0),
        child: new Text(
          "Verify and Select a Single Listing?",
          style: _textStyle,
        ),
      ),
      ListView(
        shrinkWrap: true,
        padding: const EdgeInsets.all(20.0),
        children: <Widget>[
          _getListings(),
        ],
      ),
    ]));

问题在于,由于我无法在屏幕上显示任何小部件,因此列表的值为空。

任何见解都会有用。

谢谢

编辑:

如果我尝试返回列表,这就是我看到的内容: enter image description here

我不确定这是否是动态创建窗口小部件的最佳方法。

2 个答案:

答案 0 :(得分:2)

以下是您代码的一些更新:

      Widget build(BuildContext context) {
    // Scaffold is a layout for the major Material Components.

    return new Scaffold(body: new SafeArea(
        child: Container(child: Column(children: <Widget>[
          new Padding(
            padding: const EdgeInsets.all(20.0),
            child: new Text("Verify and Select a Single Listing?",),
          ),
          Expanded(child:  ListView(
            padding: const EdgeInsets.all(20.0),
            children: _getListings(), // <<<<< Note this change for the return type
          ),
          )
        ])
        )));
  }

  List _listings = new List();

  List<Widget> _getListings() { // <<<<< Note this change for the return type
    List listings = new List<Widget>();
    int i = 0;
    for (i = 0; i < 5; i++) {
      listings.add(
        new RadioListTile<String>(
          title: const Text('Lafayette'),
          value: "c",
          groupValue: "x",
          onChanged: (_) {

          },
        ),
      );
    }
     return listings;
  }

上面要考虑的一些事情:

为了进行编译并用于此答案,我进行了一些更改以使代码得以实现。

  • 添加了针对重大更改的评论
  • 列表_listings 未使用
  • 您还可以在创建新对象时删除 new 关键字(新版本的dart可以处理此问题)

结果:

enter image description here

答案 1 :(得分:0)

对上一个答案的一些评论;

  • 请不要使用不必要的容器,如果一个容器只有一个孩子而没有其他东西,请将其删除。
  • 不必使用new关键字,Dart linters甚至告诉您不要使用它。 Like here..

如果您的列表不变,则可以使用List.unmodifiable,如以下示例所示。

final List<Widget> widgets = List.unmodifiable(() sync* {
  for (int i = 0; i < 5; i++) {
    yield RadioListTile<String>(
      title: const Text('Lafayette'),
      value: "c",
      groupValue: "x",
      onChanged: (_) {

      },
    );
  }
}());