Force Flutter navigator to reload state when popping - flutter

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

Related

How to automatically show an alert dialog without pressing a button in Flutter?

I implemented the alert dialog in the initstate() method but Init state is only called once. In my case I want the alert to appear automatically every time a variable value changes for exemple. ( I need it to suddenly pop up during using the app)
You could use a ValueNotifier and a ValueListenableBuilder so that every time the value in the ValueNotifier changes, the ValueListenableBuilder rebuilds and shows a dialog, like so:
class MyWidget extends StatelessWidget {
ValueNotifier<int> dialogTrigger = ValueNotifier(0);
#override
Widget build(BuildContext context) {
return Column(
children: [
TextButton(
onPressed: () {
var random = Random();
dialogTrigger.value = random.nextInt(100);
},
child: const Text('Click me and change a value')
),
Expanded(
child: ValueListenableBuilder(
valueListenable: dialogTrigger,
builder: (ctx, value, child) {
Future.delayed(const Duration(seconds: 0), () {
showDialog(
context: ctx,
builder: (ctx) {
return AlertDialog(
title: const Text('Dialog'),
content: Text('Hey! I got a $value'),
);
});
});
return const SizedBox();
})
)
]
);
}
}
(Again, I'm only adding a button to change the value, not to launch the dialog. That way you can programmatically change the value, which eventually launches the dialog). See if that works for your purposes.

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 use provider to create a commit/discard changes pattern?

What would be a best practice for (provider based) state management of modal widgets in flutter, where when user makes an edit changes do not propagate to parent page until user confirms/closes modal widget. Optionally, user has a choice to discard the changes.
In a nutshell:
modal widget with OK and cancel actions, or
modal widget where changes are applied when modal is closed
Currently, my solution looks like this
Create a copy of the current state
Call flutter's show___() function and wrap widgets with a provider (using .value constructor) to expose copy of the state
If needed, update original state when modal widget is closed
Example of case #2:
Future<void> showEditDialog() async {
// Create a copy of the current state
final orgState = context.read<MeState>();
final tmpState = MeState.from(orgState);
// show modal widget with new provider
await showDialog<void>(
context: context,
builder: (_) => ChangeNotifierProvider<MeState>.value(
value: tmpState,
builder: (context, _) => _buildEditDialogWidgets(context)),
);
// update original state (no discard option to keep it simple)
orgState.update(tmpState);
}
But there are issues with this, like:
Where should I dispose tmpState?
ProxyProvider doesn't have .value constructor.
If temporary state is created in Provider's create: instead, how can I safely access that temporary state when modal is closed?
UPDATE: In my current app I have a MultiProvider widget at the top of widget tree, that creates and provides multiple filter state objects. Eg. FooFiltersState, BarFiltersState and BazFiltersState. They are separate classes because each these three extends either ToggleableCollection<T> extends ChangeNotifier or ToggleableCollectionPickerState<T> extends ToggleableCollection<T> class. An abstract base classes with common properties and functions (like bool areAllSelected(), toggleAllSelection() etc.).
There is also FiltersState extends ChangeNotifier class that contains among other things activeFiltersCount, a value depended on Foo, Bar and Baz filters state. That's why I use
ChangeNotifierProxyProvider3<
FooFiltersState,
BarFilterState,
BazFilterState,
FiltersState>
to provide FiltersState instance.
User can edit these filters by opening modal bottom sheet, but changes to filters must not be reflected in the app until bottom sheet is closed by taping on the scrim. Changes are visible on the bottom sheet while editing.
Foo filters are displayed as chips on the bottom sheet. Bar and baz filters are edited inside a nested dialog windows (opened from the bottom sheet). While Bar or Baz filter collection is edited, changes must be reflected only inside the nested dialog window. When nested dialog is confirmed changes are now reflected on bottom sheet. If nested dialog is canceled changes are not transferred to the bottom sheet. Same as before, these changes are not visible inside the app until the bottom sheet is closed.
To avoid unnecessary widget rebuilds, Selector widgets are used to display filter values.
From discussion with yellowgray, I think that I should move all non-dependent values out of proxy provider. So that, temp proxy provider can create new temp state object that is completely independent of original state object. While for other objects temp states are build from original states and passed to value constructors like in the above example.
1. Where should I dispose tmpState?
I think for your case, you don't need to worry about it. tmpState is like a temporary variabl inside function showEditDialog()
2. ProxyProvider doesn't have .value constructor.
It doesn't need to because it already is. ProxyProvider<T, R>: T is a provider that need to listen to. In your case it is the orgState. But I think the orgState won't change the value outside of this function, so I don't know why you need it.
3. If temporary state is created in Provider's create: instead, how can I safely access that temporary state when modal is closed?
you can still access the orgState inside _buildEditDialogWidgets and update it by context.read(). But I think you shouldn't use same type twice in the same provider tree (MeState)
Actually when I first see your code, I will think why you need to wrap tmpState as another provider (your _buildEditDialogWidgets contains more complicated sub-tree or something else that need to use the value in many different widget?). Here is the simpler version I can think of.
Future<void> showEditDialog() async {
// Create a copy of the current state
final orgState = context.read<MeState>();
// show modal widget with new provider
await showDialog<void>(
context: context,
builder: (_) => _buildEditDialogWidgets(context,MeState.from(orgState)),
);
}
...
Widget _buildEditDialogWidgets(context, model){
...
onSubmit(){
context.read<MeState>().update(updatedModel)
}
...
}
The simplest way is you can just provide a result when you pop your dialog and use that result when updating your provider.
import 'dart:collection';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class Item {
Item(this.name);
String name;
Item clone() => Item(name);
}
class MyState extends ChangeNotifier {
List<Item> _items = <Item>[];
UnmodifiableListView<Item> get items => UnmodifiableListView<Item>(_items);
void add(Item item) {
if (item == null) {
return;
}
_items.add(item);
notifyListeners();
}
void update(Item oldItem, Item newItem) {
final int indexOfItem = _items.indexOf(oldItem);
if (newItem == null || indexOfItem < 0) {
return;
}
_items[indexOfItem] = newItem;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
#override
Widget build(_) {
return ChangeNotifierProvider<MyState>(
create: (_) => MyState(),
builder: (_, __) => MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Builder(
builder: (BuildContext context) => Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
FlatButton(
onPressed: () => _addItem(context),
child: const Text('Add'),
),
Expanded(
child: Consumer<MyState>(
builder: (_, MyState state, __) {
final List<Item> items = state.items;
return ListView.builder(
itemCount: items.length,
itemBuilder: (_, int index) => GestureDetector(
onTap: () => _updateItem(context, items[index]),
child: ListTile(
title: Text(items[index].name),
),
),
);
},
),
),
],
),
),
),
),
),
);
}
Future<void> _addItem(BuildContext context) async {
final Item item = await showDialog<Item>(
context: context,
builder: (BuildContext context2) => AlertDialog(
actions: <Widget>[
FlatButton(
onPressed: () => Navigator.pop(context2),
child: const Text('Cancel'),
),
FlatButton(
onPressed: () => Navigator.pop(
context2,
Item('New Item ${Random().nextInt(100)}'),
),
child: const Text('ADD'),
),
],
),
);
Provider.of<MyState>(context, listen: false).add(item);
}
Future<void> _updateItem(BuildContext context, Item item) async {
final Item updatedItem = item.clone();
final Item tempItem = await showModalBottomSheet<Item>(
context: context,
builder: (_) {
final TextEditingController controller = TextEditingController();
controller.text = updatedItem.name;
return Container(
height: 300,
child: Column(
children: <Widget>[
Text('Original: ${item.name}'),
TextField(
controller: controller,
enabled: false,
),
TextButton(
onPressed: () {
updatedItem.name = 'New Item ${Random().nextInt(100)}';
controller.text = updatedItem.name;
},
child: const Text('Change name'),
),
TextButton(
onPressed: () => Navigator.pop(context, updatedItem),
child: const Text('UPDATE'),
),
TextButton(
onPressed: () => Navigator.pop(context, Item(null)),
child: const Text('Cancel'),
),
],
),
);
},
);
if (tempItem != null && tempItem != updatedItem) {
// Do not update if "Cancel" is pressed.
return;
}
// Update if "UPDATE" is pressed or dimissed.
Provider.of<MyState>(context, listen: false).update(item, updatedItem);
}
}

Set barrier dismissible after dialog shown

This is the way I normally set the dialog's barrierDismissible field to true or false
showDialog(
barrierDismissible: false,
builder: ...
)
However, it implies that dialog is ALWAYS true or false.
Is there any way to start a dialog barrierDismissible as false and change it to true after one second?
It looks like flutter declarative approach wasn't applied to this widget. Therefore you should do everything yourself.
First handle yourself the tap with:
A general gesture detector which will be used to dismiss the dialog.
A gesture detector around your dialog in order to prevent the tap event to bubble up if it happened in the widget inside your dialog.
Second use a variable to state if the barrierDismissible should be activated or not, and modify this variable after 1 second. This is the variable which should be used be the general gesture detector in order to know if it should dismiss the dialog or not.
Here is a quick exemple, just tap the FAB:
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
home: MyApp(),
),
);
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool barrierDismissible = false;
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
barrierDismissible = false;
Future.delayed(
Duration(seconds: 1),
() => setState(() {
barrierDismissible = true;
}));
return GestureDetector(
onTap: () {
if (barrierDismissible) {
Navigator.of(context, rootNavigator: true).pop();
}
},
child: Material(
color: Colors.transparent,
child: GestureDetector(
onTap: () {},
child: Center(
child: Container(
height: 200,
width: 200,
color: Colors.red,
),
),
),
),
);
},
);
},
),
);
}
}
create bool variable and set that to the barrierDismissible property and use Future.delayed(duration:Duration(seconds:1)) to mak one second count then when the counter completes set the variable to true like this.
onPressed:(){
bool dismissible=false;
showDialog(context: context,barrierDismissible: dismissible); //add your child
Future.delayed(Duration(seconds: 1)).whenComplete(() {
setState(() {
dismissible=true;
});
});
}

Open flutter dialog after navigation

I call Navigator pushReplacement to show a new view within my flutter app and want to immediately pop up a simple dialog to introduce the page to the user. (I want the user to be able to see the new view in the background)
If I call showDialog within the build method of a widget, and then subsequently return a widget (scaffold) from the build method I get errors stating that flutter is already drawing a widget. I expect I need to listen on a build complete event and then call showDialog.
Guidance on how to do that much appreciated.
You can call the dialog from inside 'initState()' dalaying its appearance after the first frame has been drawn.
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
await showDialog<String>(
context: context,
builder: (BuildContext context) => new AlertDialog(
title: new Text("title"),
content: new Text("Message"),
actions: <Widget>[
new FlatButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
);
});
}
The context variable is always available inside the State class. It points to the RenderObject of this widget. The problem is that in initState() the context is not yet created so you have to defer its usage after the first frame has been laid out. Then it is available.
Another way of doing it is using Timer.run(...)
#override
void initState() {
super.initState();
// simply use this
Timer.run(() {
showDialog(
context: context,
builder: (_) => AlertDialog(title: Text("Dialog title")),
);
});
}
If anyone after a solution to display dialog based on the widget value update.
For example, let users know the screen they are trying to view, has been deleted.
if (xxx.timestamps.deleted == null) {
return DetailView(xxx: xxx);
} else {
return FutureBuilder(
future: Future.delayed(
Duration.zero,
() => showDialog(
context: context,
builder: (_) => ActionDialog(
title: Text('xxx Deleted'),
content: Text('xxx deleted'),
confirmActions: [DialogConfirm.Ok])).then(
(value) => Navigator.pop(context),
),
),
builder: (context, _) => DetailView(xxx: xxx),
);
}
kudos to https://stackoverflow.com/a/64017240/2641128