如何将小部件动态添加到 Flutter 中的列?

How to add the widgets dynamically to column in Flutter?

我在 ListView 中添加了一些小部件。这样我就可以滚动所有小部件。现在我需要再添加一个小部件到 ListView 以加载评论列表。我无法在 ListView 中添加 ListView。而且,我的评论不需要单独的卷轴。它应该与 ListView 内的小部件一起滚动。所以我计划添加 Column 而不是 ListView。在 Columns 中动态添加我的评论有什么帮助吗?

new Expanded(
          child:
          new ListView(
            shrinkWrap: true,
            children: <Widget>[

              // Title

              new Padding(padding: const EdgeInsets.only(
                  top: 10.00, left: 10.00),
                child: new Text(
                  _feed.title, textAlign: TextAlign.start,),
              ),

              // content

              new Container(
                child: new Text(
                  _feed.content, textAlign: TextAlign.start,),
              ),

              // Comments List will go here

            ],
          ),
        ),

如果您已有评论数据,只需创建一个列表,然后将其传递给Columnchildren 属性。类似于:

var commentWidgets = List<Widget>();
for (var comment in comments) {
  commentWidgets.Add(Text(comment.text)); // TODO: Whatever layout you need for each widget.
}
…

new Expanded(
      child:
      new ListView(
        shrinkWrap: true,
        children: <Widget>[

          // Title

          new Padding(padding: const EdgeInsets.only(
              top: 10.00, left: 10.00),
            child: new Text(
              _feed.title, textAlign: TextAlign.start,),
          ),

          // content

          new Container(
            child: new Text(
              _feed.content, textAlign: TextAlign.start,),
          ),

          // Comments List will go here
          Column(children: commentWidgets,),
        ],
      ),
    ),

如果您还没有评论数据并且需要获取它,请使用 FutureBuilder 在未来完成后构建 UI。

import 'package:flutter/material.dart';

class LoginRegisterPage extends StatefulWidget {
  @override
  _LoginRegisterPageState createState() => _LoginRegisterPageState();
}

class _LoginRegisterPageState extends State<LoginRegisterPage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("App"),
      ),
      body: new Container(
        margin: EdgeInsets.all(15.0),
        child: new Form(
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: createInputs() + createButtons(),
          ),
          ),
      ),
    );
  } 

  List<Widget> createInputs(){
    return{
      SizedBox(height: 10.0),
      logo(),
      SizedBox(height: 20.0),
      new TextFormField(
        decoration: new InputDecoration(labelText: 'Email'),
      ),

      SizedBox(height: 10.0),
      new TextFormField(
        decoration: new InputDecoration(labelText: 'Passwors')
      ),
      SizedBox(height: 20.0), 
    };
  }

  Widget logo(){
      return new Hero(        
        tag:'hero',
        child: new CircleAvatar(
          backgroundColor:Colors.transparent,
          radius: 110.0,
          child: Image.asset("images\logo.PNG"),          
        ),         
        );
    }

    List<Widget> createButtons(){
    return{
      new RaisedButton(
        child: new Text("Login", style: new TextStyle(fontSize: 20.0),),
        textColor: Colors.pink,         
        onPressed: () {          
        },
        ),  

        new FlatButton(
        child: new Text("Already not have an account?", style: new TextStyle(fontSize: 14.0),),
        textColor: Colors.white,         
        onPressed: () {
        }, 
        )  
    };
  }
}

通过维护对 Column 对象的引用,可以在声明 Column 对象后引用 .children field/property - 像这样:

Column someColumn = Column(
  children: [],
);

someColumn.children.add(Text('Hello 123'));

除了@Derek Lakin's Answer 对我也有用,如果你需要更新评论和重新加载,还需要调用setState()

var commentWidgets = List<Widget>();
for (var comment in comments) {
      commentWidgets.Add(Text(comment.text)); // TODO: Whatever layout you need foreach widget.
}
setState(() {

});

目前(2021-06),Flutter 2.x 实现了 null-safe。 @Gene Bo 的回答应该可以,但需要稍作修改。

这应该有效。

var pwdWidgets = <Widget>[];

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  crossAxisAlignment: CrossAxisAlignment.center,
  children: this.pwdWidgets,
),

ElevatedButton(
  onPressed: (){
    setState((){
      this.pwdWidgets.add(Text("Hello World"),);
    });
  },
  child: Text("click me"),
),

是的,您可以在列小部件上添加动态子项。

 class CategoriesItemWidget extends StatelessWidget {
  final List<String> list;

  const CategoriesItemWidget({Key? key, required this.list})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: list
          .map((string) => Text(string))
          .toList(),
    );
  }
}

另一种方式:

return Column(
      children: [
        for(String item in list) Text(item);

    ]);

在这种情况下,您还可以轻松混合静态和动态字段:

return Column(
          children: [
            for(String item in list) Text(item),
          Text("Static text control"),
   
        ]);