【问题标题】:How does one create a List of ListTile's in Flutter?如何在 Flutter 中创建 ListTile 的列表?
【发布时间】:2018-09-13 02:00:15
【问题描述】:

我的目标是拥有一个 ListTiles 列表,以便跟踪,能够添加/删除以后可以在 ListView 中显示的项目。这是我的代码的简化版本:

class Notes extends StatefulWidget{

  List<ListTile> notes;

  _NotesState createState() => new _NotesState();
}

class _NotesState extends State<Notes>{

  @override
  Widget build(BuildContext context){

     widget.notes.add(new ListTile(title: new Text("Title")));

     return new ListView(
       children: <ListTile>[
          notes[0],
       ]
     );
  }
}

但我收到以下信息:

NoSuchMethodError:在 null 上调用了方法 'add。 接收方:空 尝试调用:add(Instance of 'ListTile')

我认为应该可以这样做,当然我可能会弄错。提前感谢您帮助我解决我可能很愚蠢的问题。

【问题讨论】:

    标签: android ios mobile dart flutter


    【解决方案1】:

    问题有两个:1)您的注释字段可能未初始化。 2)您将状态存储在State 对象之外。相反,将您的笔记放在您的状态对象中并像这样初始化成员:

    class _NotesState extends State<Notes>{
      List<ListTile> notes = [
        new ListTile(title: new Text("Title")),
      ];
    
      @override
      Widget build(BuildContext context){
         return new ListView(
           children: <ListTile>[
              notes[0],
           ]
         );
      }
    }
    

    像这样的可变数据需要在State 中的原因是小部件本身可能会被重建数十次,从而擦除所有笔记。 例如,如果您的小部件是动画的子级,它将每秒重建 60 次。这也意味着您根本不应该在构建方法中更改数据,因为它的调用频率可能比您想象的要高。

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2020-06-23
      • 2020-05-28
      • 2019-04-03
      • 2018-04-16
      • 1970-01-01
      • 2021-07-03
      • 2020-02-12
      • 1970-01-01
      相关资源
      最近更新 更多