'refresh data on home page using future builder on button click - flutter
i have an app with two screens, home and update page. The home page displays a list of items and the update page updates the items.
I am having difficulties refreshing the home page to display current updates when I pop back to it.
How can I refresh the home page when I route back to it.
See the code to navigate to update page
// home page
// build the list widget
Widget _buildTaskWidget(task) {
return ListTile(
leading: Icon(Icons.assignment),
title: Text(task['name']),
subtitle: Text(task['created_at']),
onTap: () async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => UpdateTask(task: task),
),
);
await fetchAllTask();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: fetchAllTask(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List tasks = snapshot.data;
listItems = tasks;
return _buildTaskList(tasks);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Center(
child: ShowLoader(),
);
}),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => AddTask()));
},
tooltip: 'Add Task',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
// update page to navigate back to home page
onPressed: () async {
var res = await updateNewTask(_taskTextInput.text,
_vendorTextInput.text, _amountTextInput.text, id);
print(res);
Navigator.pop(context);
},
Solution 1:[1]
FutureBuilder only runs the asynchronous task when its parent is built. To force a rebuild, you can call setState()
after Navigating to the next page. Doing so refreshes the current Screen before navigating to the next.
Navigator.of(context).push(...).then((_) => setState(() {}));
Another approach that you can also consider looking into is with the use of StreamBuilder - this Widget rebuilds when change in Stream is detected.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Omatt |