Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

dart - Show a snackbar after navigate in Flutter

After an action (for example, "save"), user is returned to another page in the app.

I want to show a snackbar on the new page to confirm the action, but don't want it to show if the user navigated there without the action. So for example, if user saves "thing", the app sends them to "things" main page and shows the "saved" snackbar, but if they go to "things" main page some other way, I don't want the "saved" snackbar to be there.

Here is my code on the panel that saves, but the destination page does not show the snackbar — regardless where I place the snackbar (before or after navigation), it does not execute the snackbar.

Future<Null> saveThatThing() async {
  thing.save();
  thing = new Thing();
  Navigator.of(context).push(getSavedThingRoute());
  Scaffold.of(context).showSnackBar(
    new SnackBar(
      content: new Text('You saved the thing!'),
    ),
  );
}

What is the best way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What about if you create key for the screen Scaffold like this (put this object inside the screen state class):

final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();

and then set this variable to the Scaffold key like this:

return new Scaffold(
  key: scaffoldKey,
  appBar: new AppBar(
    .......,
  ),

and at the end to show the SnackBar just use somewhere inside the screen state class this code :

scaffoldKey.currentState
    .showSnackBar(new SnackBar(content: new Text("Hello")));

or you can wrap the latest code in method like this :

void showInSnackBar(String value) {
scaffoldKey.currentState
    .showSnackBar(new SnackBar(content: new Text(value)));}

and then just call this method and pass the snack bar message inside.

If you want to show the snack bar message on the next screen, after you navigate away from the initial context, just call the snack bar method on the next screen, not on the first screen.

Hope this will help


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...