Skip to content

Instantly share code, notes, and snippets.

@PiN73
Last active May 17, 2019 16:19
Show Gist options
  • Save PiN73/55549e86e416a518ad5e5ecbb34b3bb4 to your computer and use it in GitHub Desktop.
Save PiN73/55549e86e416a518ad5e5ecbb34b3bb4 to your computer and use it in GitHub Desktop.
Flutter - access BLoC from pushed page using nested Navigator
class BasicNavigator extends Navigator {
BasicNavigator({Key key, @required WidgetBuilder rootBuilder})
: super(
key: key,
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder(
pageBuilder: (BuildContext context, _, __) {
return rootBuilder(context);
},
);
},
);
}
class PopNavigator extends StatelessWidget {
final _navigatorKey = GlobalKey<NavigatorState>();
final WidgetBuilder rootBuilder;
PopNavigator({Key key, @required this.rootBuilder}) : super(key: key);
@override
Widget build(BuildContext context) {
return WillPopScope(
child: BasicNavigator(
key: _navigatorKey,
rootBuilder: rootBuilder,
),
onWillPop: () async {
return !await _navigatorKey.currentState.maybePop();
},
);
}
}
class RootPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
bloc: _myBloc, // any BLoC that can be used in FirstPage / SecondPage
child: PopNavigator(
rootBuilder (_) => FirstPage(),
),
);
}
}
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First page'),
),
body: Center(
child: Column(
children: <Widget>[
BlocBuilder(
bloc: BlocProvider.of<MyBloc>(context),
builder: (context, state) {
return Text(state.data);
},
),
RaisedButton(
child: Text('Open second page'),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => SecondPage(),
),
);
},
),
],
),
),
);
}
}
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second page'),
),
body: Center(
child: Column(
children: <Widget>[
BlocBuilder(
bloc: BlocProvider.of<MyBloc>(context),
builder: (context, state) {
return Text(state.data);
},
),
RaisedButton(
child: Text('Back to first page'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment