Last active
April 29, 2020 19:10
-
-
Save t-artikov/17b87025ece847763abb9a41437b06a2 to your computer and use it in GitHub Desktop.
flutter navigator test
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'; | |
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.pop(); | |
} | |
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