Created
October 31, 2018 20:21
-
-
Save MariaMelnik/0bbbc0138ce369a4b352acce3d45abf7 to your computer and use it in GitHub Desktop.
Flutter: show snackbar once after navigation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(new MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return new MaterialApp( | |
title: 'Flutter Demo', | |
theme: new ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: new MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
_MyHomePageState createState() => new _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
void goSecond(){ | |
Navigator.of(context).push(MaterialPageRoute(builder: (context) => SecondPage())); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Center( | |
child: RaisedButton( | |
onPressed: goSecond, | |
child: Text("go next"), | |
), | |
), // This trailing comma makes auto-formatting nicer for build methods. | |
); | |
} | |
} | |
class SecondPage extends StatefulWidget{ | |
@override | |
State<StatefulWidget> createState() => SecondPageState(); | |
} | |
class SecondPageState extends State<SecondPage> { | |
ScaffoldState scaffold; | |
@override | |
void initState(){ | |
super.initState(); | |
WidgetsBinding.instance | |
.addPostFrameCallback((_) => showSnackBar()); | |
} | |
void showSnackBar(){ | |
scaffold.showSnackBar(SnackBar(content: Text("snackbar"))); | |
} | |
void goThird(){ | |
Navigator.of(context).push(MaterialPageRoute(builder: (context) => ThirdPage())); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text("Second"), | |
), | |
body: Builder( | |
builder: (BuildContext buildContext) { | |
scaffold = Scaffold.of(buildContext); | |
return Center( | |
child: FlatButton(onPressed: goThird, child: Text("go next")) | |
); | |
}, | |
), | |
); | |
} | |
} | |
class ThirdPage extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text("Third"), | |
), | |
body: Center( | |
child: Text("third page") | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works for me! Thank you!