[英]How to add children to the column dynamically in flutter
如何在 flutter 的列中添加 4 个孩子,或者在某些情况下它将是 3 或 2。
Column(
children: <Widget>[_weatherData],
)
如果要动态添加 Widget,
List<Widget> data() {
List<Widget> list = List();
//i<5, pass your dynamic limit as per your requirment
for (int i = 0; i < 5; i++) {
list.add(Text("Index $i"));//add any Widget in place of Text("Index $i")
}
return list;// all widget added now retrun the list here
}
现在将此列表添加到您的列中,
Column(
mainAxisSize: MainAxisSize.max,
children: data(),
),
OutPut:
如果您事先知道要添加哪些小部件,则可以在构建子组件时使用内联if
语句:
Column(
children: <Widget>[
if(condition1)
widget1,
if(condition2)
widget2,
_ weatherData,
],)
或者,如果您事先不知道,您可以调用 function 那里返回List<Widget>
。
使用扩展运算符 ( ...
),您甚至可以混合和匹配:
Column(
children: <Widget>[
if(condition1)
widget1,
if(condition2)
widget2,
_ ..._getWeatherDataWidgets(),
],)
希望这可以帮助。
您可以添加多个孩子,这很简单,如下例所示:
Column(
children: <Widget>[
Container(
padding: EdgeInsets.only(left: 40, top: 0),
child: new Image.asset('assets/images/blue_dot.png', scale: 1.5,),
),
Container(
padding: EdgeInsets.only(left: 20, top: 0),
child: new Text(content, style: new TextStyle(fontSize: 14.0, fontStyle: FontStyle.normal, color: Color(0Xff004FBA), fontWeight: FontWeight.bold),),
),
Container(
padding: EdgeInsets.only(left: 140, top: 0, bottom: 10),
child: new Text(content, style: new TextStyle(fontSize: 12.0, fontStyle: FontStyle.normal, color: Color(0Xff767676), fontWeight: FontWeight.normal,),),
)
],
或者你可以用 arrays 绑定孩子。
或者,如果 weatherData() 是 Future。 您可以使用 FutureBuilder
FutureBuilder(
builder: (context, snapshot) {
return Column(
children: snapshot.data ?? <Widget>[],
);
},
future: weatherData(),
),
Future<List<Widget>> weatherData() async{
List<Widget> list = await FetchDataFromApi.7Days();
return list;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.