Skip to content

Instantly share code, notes, and snippets.

@chunhtai
Last active April 29, 2020 23:17
Show Gist options
  • Save chunhtai/787f4e8719332cdbad1f7611a491af80 to your computer and use it in GitHub Desktop.
Save chunhtai/787f4e8719332cdbad1f7611a491af80 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
class AppState extends ChangeNotifier {
final _pages = ['Page 1', 'Page 2'];
List<String> get pages => _pages;
bool get canPop => _pages.length > 1;
bool get canPush => _pages.length < 5;
void pop() {
_pages.removeLast();
notifyListeners();
}
void push() {
_pages.add('Page ${_pages.length + 1}');
notifyListeners();
}
}
final appState = AppState();
void main() {
final app = MaterialApp(
builder: (context, _) {
return AnimatedBuilder(
animation: appState,
builder: (context, _) {
return _buildNavigator();
},
);
},
);
runApp(app);
}
Navigator _buildNavigator() {
return Navigator(
onPopPage: _popPage,
pages: appState.pages.map(_buildPage).toList(),
);
}
bool _popPage(Route<dynamic> route, dynamic result) {
final success = route.didPop(result);
if (success) {
appState.pages.removeLast();
}
return success;
}
CustomBuilderPage _buildPage(String title) {
return CustomBuilderPage<void>(
key: ValueKey(title),
routeBuilder: (context, settings) {
return MaterialPageRoute(
settings: settings,
builder: (context) {
return MyPage(title: title);
},
);
},
);
}
class MyPage extends StatelessWidget {
final String title;
const MyPage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
RaisedButton(
child: Text('Pop'),
onPressed: appState.canPop ? appState.pop : null,
),
RaisedButton(
child: Text('Push'),
onPressed: appState.canPush ? appState.push : null,
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment