How to dismiss a Dialog alert widget automatically in Flutter? - flutter

Forgive me if its a noob question or the code seems too basic, I am new to flutter.
I have done my fair share of googling but i havent been able to find a solution.
As soon as the future function starts, i want to show the Loading alert. When the API request/response is processed, if an error has occurred it should be shown in showErrorDialog, and the LoadingDialog should be dismissed automatically.
Right now, ErrorDialog shows and can be dismissed with its button, but then LoadingDialog does not get dismissed.
I can do it with Future.delayed but that is simply a work around has has too many variable outcomes. Here is dummy code:
import 'package:flutter/material.dart';
class RandomScreen extends StatefulWidget {
#override
_RandomScreenState createState() => _RandomScreenState();
}
class _RandomScreenState extends State<RandomScreen> {
Future<void> _submitApiRequest() async {
try {
_showLoadingAlert();
//processing the API request/response here.
} catch (error) {
_showErrorDialogue(error.toString());
}
}
void _showErrorDialogue(String errorMessage) {
showDialog(
context: context,
builder: (ctx) => Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Column(
children: <Widget>[
Text(errorMessage),
FlatButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(
'Dismiss',
),
),
],
),
),
);
}
void _showLoadingAlert() {
showDialog(
context: context,
builder: (ctx) => CircularProgressIndicator(),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Random Screen'),
),
body: Center(
child: RaisedButton(
onPressed: _submitApiRequest,
child: Text('Submit'),
),
),
);
}
}

The Way you are trying to do might not be the best way in case you are trying to call API and show a loading screen . I would recommend you to use ModalProgressHud
This will show a loader while you are trying to do API call and once API response received you can hide the loader using a state variable.
In case you still want to do using alert box ,
you need to call Navigator.pop as mentioned in documentation.
If the application has multiple Navigator objects, it may be necessary to call Navigator.of(context, rootNavigator: true).pop(result) to close the dialog rather than just Navigator.pop(context, result).

Related

Flutter: Android: How to call setState() from another file?

For applying app's setting configuration to take effect around app i need to trigger main's setState from appSettings file, how to do so?
Files code:
for main.dart
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(isVibrationEnabled
? "Vibration is enabled"
: "Vibration is disabled"),
MaterialButton(
color: Colors.grey,
child: Text("Open app setting"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AppSettings(),
),
);
},
)
],
),
),
),
),
);
for globalVariables.dart
bool isVibrationEnabled = false;
for appSettings.dart
class _AppSettingsState extends State<AppSettings> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: FlatButton(
color: Colors.grey,
child: Text(
isVibrationEnabled ? "Disable Vibration" : "Enable Vibration"),
onPressed: () {
setState(() {
isVibrationEnabled
? isVibrationEnabled = false
: isVibrationEnabled = true;
});
//What to do here to trigger setState() in main.dart flie
//for displaying "Vibration is enabled" or "Vibration is disabled"
//acording to the value of bool variable which is in globalVariable.dart file.
},
),
),
),
);
i have seen other answer on stackoverflow but none of them are easy to understand, if someone can answer in a easy way please
For your specific use case, I think best is to use a state management solution like Provider, BLoC, or GetX. Docs here:
https://flutter.dev/docs/development/data-and-backend/state-mgmt/options
If you want something quick and easy, you can pass the value you're listening to and a function containing setState to your new page. Normally you'd do this with a child widget rather than new page, so it might get a bit complicated -- you'll need to rebuild the entire page after the setState. Easiest way I can think of doing that is with Navigator.pushReplacement.
Some code (I wrote this in stackoverflow not my IDE so probably has errors):
class AppSettings extends StatefulWidget {
final Function callback;
final bool isVibrationEnabled;
AppSettings({
#required this.callback,
#required this.isVibrationEnabled,
});
}
...
In your AppSettingsState use:
FlatButton(
color: Colors.grey,
child: Text(
widget.isVibrationEnabled ? "Disable Vibration" : "Enable Vibration"),
onPressed: () => widget.callback(),
),
And in your main file, when creating your appsettings use something like:
MaterialButton(
color: Colors.grey,
child: Text("Open app setting"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AppSettings(
isVibrationEnabled: isVibrationEnabled,
callback: callback,
),
),
);
},
)
void Function callback() {
setState(() => isVibrationEnabled = !isVibrationEnabled);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => AppSettings(
isVibrationEnabled: isVibrationEnabled,
callback: callback,
),
),
);
}
Again, you should probably use a state management solution for this specific use case. Rebuilding a page from another page seems messy. But it should work.
And yes, you're using the callback within your callback. So you may need to put the callback near the top of your file, or outside the main function to make it work right.

How to rebuild the whole view in flutter everytime view enters the screen

I want my page to hit the API always whenever it enters a page.
For example, I am having 2 screens i.e FirstSCreen and SecondScreen.
In FirstScreen I am calling an API to fetch some data. So if the user navigates from FirstScreen to SecondScreen and then comes back to FirstScreen by pressing the back button It should hit the API in FirstScreen again.
I want to know is there any inbuilt function in flutter where I should call my methods so that it can work every time it enters the screen. I have tried using didUpdateWidget() but it is not working the way I want.
initState() is also called only once the widget is loaded ..
Please explain me
You can use async await for it. Let's say you have a button that change the route.
onPressed: () async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SecondScreen(),
),
);
ApiCall();
},
The ApiCall function will call only when user push the back on the second screen.
I have an example that might help. However, it might not cover all scenarios where your FirstScreen will always call a specific function whenever the page is displayed after coming from a different page/screen, or specifically resuming the app (coming from background -- not to be confused when coming from another screen or popping).
My example however, will always call a function when you come back from a specific screen, and you can re-implement it to other navigation functions to ensure that a specific function is always called when coming back to FirstScreen from other screens.
main.dart
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
home_page.dart
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: RaisedButton(
onPressed: () => Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => SecondPage()))
.then((value) => _reload(value)),
child: Text('Navigate to Next Page'),
),
)
],
),
);
}
Future<void> _reload(var value) async {
print(
'Home Page resumed after popping/closing SecondPage with value {$value}. Do something.');
}
}
second_page.dart
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
Navigator.pop(context, 'Passed Value');
/// It's important that returned value (boolean) is false,
/// otherwise, it will pop the navigator stack twice;
/// since Navigator.pop is already called above ^
return false;
},
child: Scaffold(
appBar: AppBar(),
body: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(child: Text('Second Page')),
],
),
),
);
}
}
#Rick's answer works like a charm even for Riverpod state management as I coul d not get the firstscreen to rebuild to show changes to the 'used' status of a coupon on the second screen where there is a button to use it.
So I did on the details page:
return WillPopScope(
onWillPop: () async {
//final dumbo = ref.read(userProvider.notifier).initializeUser();
Navigator.pop(context);
return false; //true;
},
Then on the coupons list page, each coupon card has:
child: Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24.0),
side: BorderSide(
color: coupons[index].isUsed
? Colors.grey
: Colors.blue),
),
child: InkWell(
splashColor: Colors.blue.withAlpha(30),
onTap: () {
//go to Details screen with Coupon instance
//https://api.flutter.dev/flutter/widgets/Navigator/pushNamed.html
Navigator.pushNamed(context, '/details',
arguments: coupons[index].couponId)
.then((_) => _reload());
/*Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => DetailsScreen(
coupon: coupons[index],
),
),
);*/
},
where I used _ since there is no parameter.
Then the function in class CouponScreen is:
void _reload() {
setState(() {});
}
I believe setState(){} is what triggers the rebuild. I apologize for the formatting but it's very difficult to copy and paste Flutter code that is nested deeply.

How to move to stateful page with Navigator

I'm trying to move to the next page with Navigator.
It works when I use StatelessWidget but fails with StatefulWidget.
Code that I am using:
RaisedButton(
onPressed: (){
Navigator.of(context).push(SecondPage()));
},
child: Text('Next'),
Please let me know how to push StatefulWidget Page.
Thanks.
Please use the code sample as shared in the snippet below:
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
I figured out the reason why it does not work were.
Second page does not implemented properly returned null.
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Page02'),
),
);
}

Snackbar is displayed after tapping back button

Flow is: user clicks on a link from screen 1 to go to screen 2. On screen 2, user enters required data and taps on save button that saves data and navigates to screen 1 where I want to show a snackbar.
This sounds very similar to this and this post, but it's not working for me. So, I followed this code sample which works properly, but there's one issue.
If I press app bar back button or device back button from screen 2, it still shows the snackbar on screen 1. Wondering how could I avoid this behavior of not showing snackbar after hitting back buttons.
After user saves data on screen 2, I am simply using Navigator.pop(context) that takes user to screen 1. On screen 1, I've a method that navigates to screen 2 and triggers snackbar as below:
Navigator.push(
context, MaterialPageRoute(builder: (context) => Screen2())
);
scaffoldKey.currentState.showSnackBar(SnackBar(content: Text('Show me'),));
Although this works, I don't want to show the snackbar if user clicks back button.
Problem is, your snackBar has duration, within that duration if you navigate back to the screen, you'll see that old snackBar again.
Solution is add this method before Navigator:
Scaffold.of(context).removeCurrentSnackBar();
In your case, you're using scaffoldKey, so translate it as you need. But, be sure you are contacting with right Scaffold.
scaffoldKey.currentState.removeCurrentSnackBar();
Official link:
https://api.flutter.dev/flutter/material/ScaffoldState/removeCurrentSnackBar.html
Edit: About calling Screen 1 Scaffold inside Screen 2 Scaffold:
Your screen has Scaffolds. Scaffolds have keys in your situation as I see.
Let's say Screen1 has screen1Key ScaffoldState key. Same for Screen2.
Inside Screen2 you must call
screen1Key.currentState.removeCurrentSnackBar();
full example:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Screen1(),
));
}
GlobalKey<ScaffoldState> screen1Key = GlobalKey<ScaffoldState>();
GlobalKey<ScaffoldState> screen2Key = GlobalKey<ScaffoldState>();
class Screen1 extends StatefulWidget {
#override
_Screen1State createState() => _Screen1State();
}
class _Screen1State extends State<Screen1> {
#override
Widget build(BuildContext context) {
return Scaffold(
key: screen1Key,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
onPressed: () {
screen1Key.currentState
.showSnackBar(SnackBar(content: Text('Screen 1 SnackBar')));
},
child: Text('Show SnackBar'),
),
RaisedButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return Screen2();
}));
},
child: Text('Navigate forward'),
),
],
),
),
);
}
}
class Screen2 extends StatefulWidget {
#override
_Screen2State createState() => _Screen2State();
}
class _Screen2State extends State<Screen2> {
#override
Widget build(BuildContext context) {
return Scaffold(
key: screen2Key,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
onPressed: () {
screen2Key.currentState
.showSnackBar(SnackBar(content: Text('Screen 2 SnackBar')));
},
child: Text('Show SnackBar'),
),
RaisedButton(
onPressed: () {
screen1Key.currentState.removeCurrentSnackBar();
Navigator.pop(context);
},
child: Text('Navigate Back'),
),
],
),
),
);
}
}
I hope I understand well your problem.

Force Flutter navigator to reload state when popping

I have one StatefulWidget in Flutter with button, which navigates me to another StatefulWidget using Navigator.push(). On second widget I'm changing global state (some user preferences). When I get back from second widget to first, using Navigator.pop() the first widget is in old state, but I want to force it's reload. Any idea how to do this? I have one idea but it looks ugly:
pop to remove second widget (current one)
pop again to remove first widget (previous one)
push first widget (it should force redraw)
There's a couple of things you could do here. #Mahi's answer while correct could be a little more succinct and actually use push rather than showDialog as the OP was asking about. This is an example that uses Navigator.push:
import 'package:flutter/material.dart';
class SecondPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.green,
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () => Navigator.pop(context),
child: Text('back'),
),
],
),
);
}
}
class FirstPage extends StatefulWidget {
#override
State<StatefulWidget> createState() => new FirstPageState();
}
class FirstPageState extends State<FirstPage> {
Color color = Colors.white;
#override
Widget build(BuildContext context) {
return new Container(
color: color,
child: Column(
children: <Widget>[
RaisedButton(
child: Text("next"),
onPressed: () async {
final value = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage()),
),
);
setState(() {
color = color == Colors.white ? Colors.grey : Colors.white;
});
},
),
],
),
);
}
}
void main() => runApp(
MaterialApp(
builder: (context, child) => SafeArea(child: child),
home: FirstPage(),
),
);
However, there's another way to do this that might fit your use-case well. If you're using the global as something that affects the build of your first page, you could use an InheritedWidget to define your global user preferences, and each time they are changed your FirstPage will rebuild. This even works within a stateless widget as shown below (but should work in a stateful widget as well).
An example of inheritedWidget in flutter is the app's Theme, although they define it within a widget instead of having it directly building as I have here.
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
class SecondPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.green,
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () {
ColorDefinition.of(context).toggleColor();
Navigator.pop(context);
},
child: new Text("back"),
),
],
),
);
}
}
class ColorDefinition extends InheritedWidget {
ColorDefinition({
Key key,
#required Widget child,
}): super(key: key, child: child);
Color color = Colors.white;
static ColorDefinition of(BuildContext context) {
return context.inheritFromWidgetOfExactType(ColorDefinition);
}
void toggleColor() {
color = color == Colors.white ? Colors.grey : Colors.white;
print("color set to $color");
}
#override
bool updateShouldNotify(ColorDefinition oldWidget) =>
color != oldWidget.color;
}
class FirstPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
var color = ColorDefinition.of(context).color;
return new Container(
color: color,
child: new Column(
children: <Widget>[
new RaisedButton(
child: new Text("next"),
onPressed: () {
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new SecondPage()),
);
}),
],
),
);
}
}
void main() => runApp(
new MaterialApp(
builder: (context, child) => new SafeArea(
child: new ColorDefinition(child: child),
),
home: new FirstPage(),
),
);
If you use inherited widget you don't have to worry about watching for the pop of the page you pushed, which will work for basic use-cases but may end up having problems in a more complex scenario.
Short answer:
Use this in 1st page:
Navigator.pushNamed(context, '/page2').then((_) => setState(() {}));
and this in 2nd page:
Navigator.pop(context);
There are 2 things, passing data from
1st Page to 2nd
Use this in 1st page
// sending "Foo" from 1st
Navigator.push(context, MaterialPageRoute(builder: (_) => Page2("Foo")));
Use this in 2nd page.
class Page2 extends StatelessWidget {
final String string;
Page2(this.string); // receiving "Foo" in 2nd
...
}
2nd Page to 1st
Use this in 2nd page
// sending "Bar" from 2nd
Navigator.pop(context, "Bar");
Use this in 1st page, it is the same which was used earlier but with little modification.
// receiving "Bar" in 1st
String received = await Navigator.push(context, MaterialPageRoute(builder: (_) => Page2("Foo")));
For me this seems to work:
Navigator.of(context).pushNamed("/myRoute").then((value) => setState(() {}));
Then simply call Navigator.pop() in the child.
The Easy Trick is to use the Navigator.pushReplacement method
Page 1
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Page2(),
),
);
Page 2
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Page1(),
),
);
Simply add .then((value) { setState(() {}); after Navigator.push on page1() just like below:
Navigator.push(context,MaterialPageRoute(builder: (context) => Page2())).then((value) { setState(() {});
Now when you use Navigator.pop(context) from page2 your page1 rebuild itself
You can use pushReplacement and specify the new Route
onTapFunction(BuildContext context) async {
final reLoadPage = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => IdDetailsScreen()),
);
if (reLoadPage) {
setState(() {});
}
}
Now while doing Navigator.pop from second page to come back to first page just return some value which in my case is of bool type
onTap: () {
Navigator.pop(context, true);
}
my solution went by adding a function parameter on SecondPage, then received the reloading function which is being done from FirstPage, then executed the function before the Navigator.pop(context) line.
FirstPage
refresh() {
setState(() {
//all the reload processes
});
}
then on pushing to the next page...
Navigator.push(context, new MaterialPageRoute(builder: (context) => new SecondPage(refresh)),);
SecondPage
final Function refresh;
SecondPage(this.refresh); //constructor
then on before the navigator pop line,
widget.refresh(); // just refresh() if its statelesswidget
Navigator.pop(context);
Everything that needs to be reloaded from the previous page should be updated after the pop.
This work really good, i got from this doc from flutter page: flutter doc
I defined the method to control navigation from first page.
_navigateAndDisplaySelection(BuildContext context) async {
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => AddDirectionPage()),
);
//below you can get your result and update the view with setState
//changing the value if you want, i just wanted know if i have to
//update, and if is true, reload state
if (result) {
setState(() {});
}
}
So, i call it in a action method from a inkwell, but can be called also from a button:
onTap: () {
_navigateAndDisplaySelection(context);
},
And finally in the second page, to return something (i returned a bool, you can return whatever you want):
onTap: () {
Navigator.pop(context, true);
}
Put this where you're pushing to second screen (inside an async function)
Function f;
f= await Navigator.pushNamed(context, 'ScreenName');
f();
Put this where you are popping
Navigator.pop(context, () {
setState(() {});
});
The setState is called inside the pop closure to update the data.
I had a similar issue.
Please try this out:
In the First Page:
Navigator.push( context, MaterialPageRoute( builder: (context) => SecondPage()), ).then((value) => setState(() {}));
After you pop back from SecondPage() to FirstPage() the "then" statement will run and refresh the page.
You can pass back a dynamic result when you are popping the context and then call the setState((){}) when the value is true otherwise just leave the state as it is.
I have pasted some code snippets for your reference.
handleClear() async {
try {
var delete = await deleteLoanWarning(
context,
'Clear Notifications?',
'Are you sure you want to clear notifications. This action cannot be undone',
);
if (delete.toString() == 'true') {
//call setState here to rebuild your state.
}
} catch (error) {
print('error clearing notifications' + error.toString());
}
}
Future<bool> deleteLoanWarning(BuildContext context, String title, String msg) async {
return await showDialog<bool>(
context: context,
child: new AlertDialog(
title: new Text(
title,
style: new TextStyle(fontWeight: fontWeight, color: CustomColors.continueButton),
textAlign: TextAlign.center,
),
content: new Text(
msg,
textAlign: TextAlign.justify,
),
actions: <Widget>[
new Container(
decoration: boxDecoration(),
child: new MaterialButton(
child: new Text('NO',),
onPressed: () {
Navigator.of(context).pop(false);
},
),
),
new Container(
decoration: boxDecoration(),
child: new MaterialButton(
child: new Text('YES', ),
onPressed: () {
Navigator.of(context).pop(true);
},
),
),
],
),
) ??
false;
}
Regards,
Mahi
In flutter 2.5.2 this is worked for me also it works for updating a list
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage()))
.then((value) => setState(() {}));
then in the second page I just code this
Navigator.pop(context);
I have a ListView in fist page which is display a list[] data, the second page was updating the data for my list[] so the above code works for me.
Needed to force rebuild of one of my stateless widgets. Did't want to use stateful. Came up with this solution:
await Navigator.of(context).pushNamed(...);
ModalRoute.of(enclosingWidgetContext);
Note that context and enclosingWidgetContext could be the same or different contexts. If, for example, you push from inside StreamBuilder, they would be different.
We don't do anything here with ModalRoute. The act of subscribing alone is enough to force rebuild.
If you are using an alert dialog then you can use a Future that completes when the dialog is dismissed. After the completion of the future you can force widget to reload the state.
First page
onPressed: () async {
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
....
);
}
);
setState(() {});
}
In Alert dialog
Navigator.of(context).pop();
This simple code worked for me to go to the root and reload the state:
...
onPressed: () {
Navigator.of(context).pushNamedAndRemoveUntil('/', ModalRoute.withName('/'));
},
...
In short, you should make the widget watch the state. You need state management for this.
My method is based on Provider explained in Flutter Architecture Samples as well as Flutter Docs. Please refer to them for more concise explanation but more or less the steps are :
Define your state model with states that the widget needs to observe.
You could have multiple states say data and isLoading, to wait for some API process. The model itself extends ChangeNotifier.
Wrap the widgets that depend on those states with watcher class.
This could be Consumer or Selector.
When you need to "reload", you basically update those states and broadcast the changes.
For state model the class would look more or less as follows. Pay attention to notifyListeners which broadcasts the changes.
class DataState extends ChangeNotifier{
bool isLoading;
Data data;
Future loadData(){
isLoading = true;
notifyListeners();
service.get().then((newData){
isLoading = false;
data = newData;
notifyListeners();
});
}
}
Now for the widget. This is going to be very much a skeleton code.
return ChangeNotifierProvider(
create: (_) => DataState()..loadData(),
child: ...{
Selector<DataState, bool>(
selector: (context, model) => model.isLoading,
builder: (context, isLoading, _) {
if (isLoading) {
return ProgressBar;
}
return Container(
child: Consumer<DataState>(builder: (context, dataState, child) {
return WidgetData(...);
}
));
},
),
}
);
Instance of the state model is provided by ChangeNotifierProvider. Selector and Consumer watch the states, each for isLoading and data respectively. There is not much difference between them but personally how you use them would depend on what their builders provide. Consumer provides access to the state model so calling loadData is simpler for any widgets directly underneath it.
If not then you can use Provider.of. If we'd like to refresh the page upon return from the second screen then we can do something like this:
await Navigator.push(context,
MaterialPageRoute(
builder: (_) {
return Screen2();
));
Provider.of<DataState>(context, listen: false).loadData();
For me worked:
...
onPressed: (){pushUpdate('/somePageName');}
...
pushUpdate (string pageName) async { //in the same class
await pushPage(context, pageName);
setState(() {});
}
//---------------------------------------------
//general sub
pushPage (context, namePage) async {
await Navigator.pushNamed(context, namePage);
}
In this case doesn't matter how you pop (with button in UI or "back" in android) the update will be done.
Very simply use "then" after you push, when navigator pops back it will fire setState and the view will refresh.
Navigator.push(blabla...).then((value) => setState(() {}))
// Push to second screen
await Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => SecondScreen(),
),
);
// Call build method to update any changes
setState(() {});
Use setstate in your navigation push code.
Navigator.push(context, MaterialPageRoute(builder: (context) => YourPage())).then((value) {
setState(() {
// refresh state
});
});
This simple code goes to the root and reloads the state even without setState:
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => MainPage()), (Route<dynamic> route) => false,); //// this MainPage is your page to refresh