How does one create a List of ListTile's in Flutter?
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.
Marko
Updated on December 04, 2022Comments
-
Marko over 1 year
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.