如何在flutter中动态将子级添加到列中

时间:2019-11-22 06:56:03

标签: flutter dart

如何添加4个子项,或者在某些情况下将3个或2个添加到颤振列中。

        Column(
          children: <Widget>[_weatherData],
        )

4 个答案:

答案 0 :(得分:1)

如果您事先知道要添加哪些小部件,则可以在构建子代时使用内联if语句:

Column(
     children: <Widget>[
     if(condition1)
      widget1,
     if(condition2)
     widget2,
_    weatherData,
],)

或者如果您事先不知道,则可以在那里调用返回List<Widget>的函数。

使用传播算子(...),您甚至可以混合搭配:

Column(
     children: <Widget>[
     if(condition1)
      widget1,
     if(condition2)
     widget2,
_    ..._getWeatherDataWidgets(),
],)

希望这会有所帮助。

答案 1 :(得分:0)

您可以添加多个子代,就像下面的示例一样简单:

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,),),
              )
          ],

或者您可以将子级与数组绑定。

答案 2 :(得分:0)

如果要动态添加小部件,

  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(),
    ),

输出:

enter image description here

答案 3 :(得分:0)

或者如果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;
}