在Flutter中动态生成小部件

问题描述 投票:0回答:1

我试图根据特定条件动态生成一组小部件。在这种情况下,我试图生成一个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(),
        ],
      ),
    ]));

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

任何见解都会有用。

谢谢,

编辑:

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

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

flutter
1个回答
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未使用
  • 您也可以在创建新对象时删除新关键字(新版本的dart能够处理此问题)

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.