简体   繁体   中英

How does one create a List of ListTile's in Flutter?

My goal is to have a List of ListTiles, in order to keep track, be able to add/remove items that can later be displayed in a ListView. Here is a simplified version of my code:

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

But I receive the following:

NoSuchMethodError: The method 'add was called on null. Receiver: null Tried calling: add(Instance of 'ListTile')

I presume it should be possible to do so, though of course I might be mistaken. Thank you in advance for helping me with my potentially stupid question.

The problem two fold: 1) your notes field may not be initialized. 2) you are storing state outside of the State object. Instead, place your notes inside your state object and initialize the member like this:

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

The reason mutable data like this needs to be in State is that the widget itself may be rebuilt dozens of times, erasing all of your notes. For example, if your widget is the child of an animation, it will get rebuilt 60 times a second. This also means that you shouldn't mutate data inside of a build method at all, since it may be called more often then you would think.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM