问题描述
我正在尝试根据特定条件动态生成一组小部件.在这种情况下,我试图生成RadioTiles列表
I am trying to dynamically generate a set of widgets based on a particular condition. In this case I am trying to generate a list of RadioTiles
这就是我尝试生成的方式
This is how I am trying to generate
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;
}
并且我试图在这样的有状态小部件中显示此内容:
and I am trying to display this within a stateful widget like this :
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(),
],
),
]));
问题在于,由于我无法在屏幕上显示任何小部件,所以列表的值为空.
The issue is that the value of listings is null due to which I am unable to display any widgets on the screen.
任何见解都是有用的.
谢谢
如果我确实尝试返回列表,这就是我看到的内容:
If I do try to return a list this is what I see:
我不确定这是否是动态创建窗口小部件的最佳方法.
I am not sure if this is the best way to dynamically create widgets.
推荐答案
以下是您代码的一些更新:
Here are some updates to your code:
Widget build(BuildContext context) {
return Scaffold(body: SafeArea(
child: Container(child: Column(children: <Widget>[
Padding(
padding: const EdgeInsets.all(20.0),
child: 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 = List<Widget>();
int i = 0;
for (i = 0; i < 5; i++) {
listings.add(
RadioListTile<String>(
title: const Text('Lafayette'),
value: "c",
groupValue: "x",
onChanged: (_) {
},
),
);
}
return listings;
}
上面要考虑的一些事情:
Some things to consider above:
为了进行编译并用于此答案,我已经进行了一些更改,使代码得以实现.
I've made changes to make the code in order to compile and be used for this answer.
- 添加了针对重大更改的评论
- 列表
_listings
未使用 - 您还可以在创建新对象时删除
new
关键字(新版本的dart可以处理此问题)
- added comments for notable changes
- List
_listings
is unused - you can also drop the
new
keyword when creating new objects (the new version of dart is able to handle this)
结果:
这篇关于在Flutter中动态生成小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!