Background
I am building super simple TODO list app for practicing Flutter. If you input a string and click "add", then the text is shown in the list on the upper part.
Question
When and how should I call model.getTasks()
(= update data asynchronously) and model.refresh()
(= notifyListeners
)?
I find the list is not updated immediately because I don't use await
for model.getTasks()
. I tried these but I would like to know if there are better ways.
- Use
await model.getTasks()
and makebuild
an async function. --> Compile error - Add
await model.getTasks()
right beforemodel.refresh()
. -->model.tasks
is not updated before renderingListView
when opening the app.model.getTasks()
are called twice when creating new tasks.
Screenshot
Code details
model.tasks
isList<Task>
, which is to store tasks fetched from DB (sqflite
).model.getTasks()
is an async function to fetch data from DB and overwritemodel.tasks
.model.refresh()
is only for callingnotifyListeners()
.TodoListPage
is the listener of the model'snotifyListeners
.
class TodoListPage extends StatelessWidget {
final TextEditingController _textFieldController = TextEditingController();
@override
Widget build(BuildContext context) {
print('TodoListPage.build');
final model = Provider.of<TodoListModel>(context);
model.getTasks();
Future createTask() async {
TaskData taskData = await DatabaseHandler()
.insertTask(new TaskData(name: _textFieldController.text));
model.refresh();
}
return Scaffold(
appBar: AppBar(
title: Text(
'TODO List',
),
),
body: Column(
children: <Widget>[
Container(
height: 150,
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Text(model.tasks[index].name);
},
itemCount: model.tasks.length,
),
),
Text(
'Add',
),
Form(
child: Column(
children: <Widget>[
TextFormField(
controller: _textFieldController,
),
RaisedButton(
onPressed: () {
print('onPressed');
print(_textFieldController.text);
createTask();
},
child: Text('New'),
),
],
),
)
],
),
);
}
}