I have a list of download tasks as datasource for ListView
. After the list is created, I'll start all tasks and when any task is done, I'll update task.isDone
property so changes are reflected to UI. How do I do this with setState
?:
// My list of tasks used in ListView
List<Task> _tasks;
Future<void> onl oaded() async {
// Load initial tasks.
var tasks = await loadTasks();
// Set state.
setState(() {
_tasks = tasks;
});
// Start tasks.
_tasks.map((task) async {
// When any task is done, update the state and UI.
await startDownload(task);
setState(() {
// Can I do this?
task.isDone = true;
});
});
}
CodePudding user response:
You can start your task when the first setState
finished and this means after the ui rebuild, so try this:
Future<void> onl oaded() async {
// Load initial tasks.
var tasks = await loadTasks();
// Set state.
setState(() {
_tasks = tasks;
});
WidgetsBinding.instance.addPostFrameCallback((_) { // <---- add this
// Start tasks.
_tasks.map((task) async {
// When any task is done, update the state and UI.
await startDownload(task);
setState(() {
task.isDone = true;
});
});
});
}
CodePudding user response:
if setState
is not working. try super.setState((){...})