Predictive back support for root routes (#120385)
This PR aims to support Android's predictive back gesture when popping the entire Flutter app. Predictive route transitions between routes inside of a Flutter app will come later. <img width="200" src="https://user-images.githubusercontent.com/389558/217918109-945febaa-9086-41cc-a476-1a189c7831d8.gif" /> ### Trying it out If you want to try this feature yourself, here are the necessary steps: 1. Run Android 33 or above. 1. Enable the feature flag for predictive back on the device under "Developer options". 1. Create a Flutter project, or clone [my example project](https://github.com/justinmc/flutter_predictive_back_examples). 1. Set `android:enableOnBackInvokedCallback="true"` in android/app/src/main/AndroidManifest.xml (already done in the example project). 1. Check out this branch. 1. Run the app. Perform a back gesture (swipe from the left side of the screen). You should see the predictive back animation like in the animation above and be able to commit or cancel it. ### go_router support go_router works with predictive back out of the box because it uses a Navigator internally that dispatches NavigationNotifications! ~~go_router can be supported by adding a listener to the router and updating SystemNavigator.setFrameworkHandlesBack.~~ Similar to with nested Navigators, nested go_routers is supported by using a PopScope widget. <details> <summary>Full example of nested go_routers</summary> ```dart // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:go_router/go_router.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; void main() => runApp(_MyApp()); class _MyApp extends StatelessWidget { final GoRouter router = GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => _HomePage(), ), GoRoute( path: '/nested_navigators', builder: (BuildContext context, GoRouterState state) => _NestedGoRoutersPage(), ), ], ); @override Widget build(BuildContext context) { return MaterialApp.router( routerConfig: router, ); } } class _HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Nested Navigators Example'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('Home Page'), const Text('A system back gesture here will exit the app.'), const SizedBox(height: 20.0), ListTile( title: const Text('Nested go_router route'), subtitle: const Text('This route has another go_router in addition to the one used with MaterialApp above.'), onTap: () { context.push('/nested_navigators'); }, ), ], ), ), ); } } class _NestedGoRoutersPage extends StatefulWidget { @override State<_NestedGoRoutersPage> createState() => _NestedGoRoutersPageState(); } class _NestedGoRoutersPageState extends State<_NestedGoRoutersPage> { late final GoRouter _router; final GlobalKey<NavigatorState> _nestedNavigatorKey = GlobalKey<NavigatorState>(); // If the nested navigator has routes that can be popped, then we want to // block the root navigator from handling the pop so that the nested navigator // can handle it instead. bool get _popEnabled { // canPop will throw an error if called before build. Is this the best way // to avoid that? return _nestedNavigatorKey.currentState == null ? true : !_router.canPop(); } void _onRouterChanged() { // Here the _router reports the location correctly, but canPop is still out // of date. Hence the post frame callback. SchedulerBinding.instance.addPostFrameCallback((Duration duration) { setState(() {}); }); } @override void initState() { super.initState(); final BuildContext rootContext = context; _router = GoRouter( navigatorKey: _nestedNavigatorKey, routes: [ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => _LinksPage( title: 'Nested once - home route', backgroundColor: Colors.indigo, onBack: () { rootContext.pop(); }, buttons: <Widget>[ TextButton( onPressed: () { context.push('/two'); }, child: const Text('Go to another route in this nested Navigator'), ), ], ), ), GoRoute( path: '/two', builder: (BuildContext context, GoRouterState state) => _LinksPage( backgroundColor: Colors.indigo.withBlue(255), title: 'Nested once - page two', ), ), ], ); _router.addListener(_onRouterChanged); } @override void dispose() { _router.removeListener(_onRouterChanged); super.dispose(); } @override Widget build(BuildContext context) { return PopScope( popEnabled: _popEnabled, onPopped: (bool success) { if (success) { return; } _router.pop(); }, child: Router<Object>.withConfig( restorationScopeId: 'router-2', config: _router, ), ); } } class _LinksPage extends StatelessWidget { const _LinksPage ({ required this.backgroundColor, this.buttons = const <Widget>[], this.onBack, required this.title, }); final Color backgroundColor; final List<Widget> buttons; final VoidCallback? onBack; final String title; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: backgroundColor, body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(title), //const Text('A system back here will go back to Nested Navigators Page One'), ...buttons, TextButton( onPressed: onBack ?? () { context.pop(); }, child: const Text('Go back'), ), ], ), ), ); } } ``` </details> ### Resources Fixes https://github.com/flutter/flutter/issues/109513 Depends on engine PR https://github.com/flutter/engine/pull/39208 ✔️ Design doc: https://docs.google.com/document/d/1BGCWy1_LRrXEB6qeqTAKlk-U2CZlKJ5xI97g45U7azk/edit# Migration guide: https://github.com/flutter/website/pull/8952
This commit is contained in:
committed by
GitHub
parent
daf5827975
commit
dedd100ebd
@@ -71,14 +71,10 @@ class _HomeState extends State<Home> with TickerProviderStateMixin<Home> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return WillPopScope(
|
||||
onWillPop: () async {
|
||||
return NavigatorPopHandler(
|
||||
onPop: () {
|
||||
final NavigatorState navigator = navigatorKeys[selectedIndex].currentState!;
|
||||
if (!navigator.canPop()) {
|
||||
return true;
|
||||
}
|
||||
navigator.pop();
|
||||
return false;
|
||||
},
|
||||
child: Scaffold(
|
||||
body: SafeArea(
|
||||
|
||||
166
examples/api/lib/widgets/form/form.1.dart
Normal file
166
examples/api/lib/widgets/form/form.1.dart
Normal file
@@ -0,0 +1,166 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// This sample demonstrates showing a confirmation dialog when the user
|
||||
/// attempts to navigate away from a page with unsaved [Form] data.
|
||||
|
||||
void main() => runApp(const FormApp());
|
||||
|
||||
class FormApp extends StatelessWidget {
|
||||
const FormApp({
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Confirmation Dialog Example'),
|
||||
),
|
||||
body: Center(
|
||||
child: _SaveableForm(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SaveableForm extends StatefulWidget {
|
||||
@override
|
||||
State<_SaveableForm> createState() => _SaveableFormState();
|
||||
}
|
||||
|
||||
class _SaveableFormState extends State<_SaveableForm> {
|
||||
final TextEditingController _controller = TextEditingController();
|
||||
String _savedValue = '';
|
||||
bool _isDirty = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller.addListener(_onChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.removeListener(_onChanged);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onChanged() {
|
||||
final bool nextIsDirty = _savedValue != _controller.text;
|
||||
if (nextIsDirty == _isDirty) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_isDirty = nextIsDirty;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _showDialog() async {
|
||||
final bool? shouldDiscard = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Are you sure?'),
|
||||
content: const Text('Any unsaved changes will be lost!'),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
child: const Text('Yes, discard my changes'),
|
||||
onPressed: () {
|
||||
Navigator.pop(context, true);
|
||||
},
|
||||
),
|
||||
TextButton(
|
||||
child: const Text('No, continue editing'),
|
||||
onPressed: () {
|
||||
Navigator.pop(context, false);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (shouldDiscard ?? false) {
|
||||
// Since this is the root route, quit the app where possible by invoking
|
||||
// the SystemNavigator. If this wasn't the root route, then
|
||||
// Navigator.maybePop could be used instead.
|
||||
// See https://github.com/flutter/flutter/issues/11490
|
||||
SystemNavigator.pop();
|
||||
}
|
||||
}
|
||||
|
||||
void _save(String? value) {
|
||||
setState(() {
|
||||
_savedValue = value ?? '';
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
const Text('If the field below is unsaved, a confirmation dialog will be shown on back.'),
|
||||
const SizedBox(height: 20.0),
|
||||
Form(
|
||||
canPop: !_isDirty,
|
||||
onPopInvoked: (bool didPop) {
|
||||
if (didPop) {
|
||||
return;
|
||||
}
|
||||
_showDialog();
|
||||
},
|
||||
autovalidateMode: AutovalidateMode.always,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
TextFormField(
|
||||
controller: _controller,
|
||||
onFieldSubmitted: (String? value) {
|
||||
_save(value);
|
||||
},
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
_save(_controller.text);
|
||||
},
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
const Text('Save'),
|
||||
if (_controller.text.isNotEmpty)
|
||||
Icon(
|
||||
_isDirty ? Icons.warning : Icons.check,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (_isDirty) {
|
||||
_showDialog();
|
||||
return;
|
||||
}
|
||||
// Since this is the root route, quit the app where possible by
|
||||
// invoking the SystemNavigator. If this wasn't the root route,
|
||||
// then Navigator.maybePop could be used instead.
|
||||
// See https://github.com/flutter/flutter/issues/11490
|
||||
SystemNavigator.pop();
|
||||
},
|
||||
child: const Text('Go back'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// This sample demonstrates using [NavigatorPopHandler] to handle system back
|
||||
/// gestures when there are nested [Navigator] widgets by delegating to the
|
||||
/// current [Navigator].
|
||||
|
||||
void main() => runApp(const NavigatorPopHandlerApp());
|
||||
|
||||
class NavigatorPopHandlerApp extends StatelessWidget {
|
||||
const NavigatorPopHandlerApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
initialRoute: '/',
|
||||
routes: <String, WidgetBuilder>{
|
||||
'/': (BuildContext context) => _HomePage(),
|
||||
'/nested_navigators': (BuildContext context) => const NestedNavigatorsPage(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HomePage extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Nested Navigators Example'),
|
||||
),
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
const Text('Home Page'),
|
||||
const Text('A system back gesture here will exit the app.'),
|
||||
const SizedBox(height: 20.0),
|
||||
ListTile(
|
||||
title: const Text('Nested Navigator route'),
|
||||
subtitle: const Text('This route has another Navigator widget in addition to the one inside MaterialApp above.'),
|
||||
onTap: () {
|
||||
Navigator.of(context).pushNamed('/nested_navigators');
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NestedNavigatorsPage extends StatefulWidget {
|
||||
const NestedNavigatorsPage({super.key});
|
||||
|
||||
@override
|
||||
State<NestedNavigatorsPage> createState() => _NestedNavigatorsPageState();
|
||||
}
|
||||
|
||||
class _NestedNavigatorsPageState extends State<NestedNavigatorsPage> {
|
||||
final GlobalKey<NavigatorState> _nestedNavigatorKey = GlobalKey<NavigatorState>();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return NavigatorPopHandler(
|
||||
onPop: () {
|
||||
_nestedNavigatorKey.currentState!.maybePop();
|
||||
},
|
||||
child: Navigator(
|
||||
key: _nestedNavigatorKey,
|
||||
initialRoute: 'nested_navigators/one',
|
||||
onGenerateRoute: (RouteSettings settings) {
|
||||
switch (settings.name) {
|
||||
case 'nested_navigators/one':
|
||||
final BuildContext rootContext = context;
|
||||
return MaterialPageRoute<void>(
|
||||
builder: (BuildContext context) => NestedNavigatorsPageOne(
|
||||
onBack: () {
|
||||
Navigator.of(rootContext).pop();
|
||||
},
|
||||
),
|
||||
);
|
||||
case 'nested_navigators/one/another_one':
|
||||
return MaterialPageRoute<void>(
|
||||
builder: (BuildContext context) => const NestedNavigatorsPageTwo(
|
||||
),
|
||||
);
|
||||
default:
|
||||
throw Exception('Invalid route: ${settings.name}');
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NestedNavigatorsPageOne extends StatelessWidget {
|
||||
const NestedNavigatorsPageOne({
|
||||
required this.onBack,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final VoidCallback onBack;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.grey,
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
const Text('Nested Navigators Page One'),
|
||||
const Text('A system back here returns to the home page.'),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pushNamed('nested_navigators/one/another_one');
|
||||
},
|
||||
child: const Text('Go to another route in this nested Navigator'),
|
||||
),
|
||||
TextButton(
|
||||
// Can't use Navigator.of(context).pop() because this is the root
|
||||
// route, so it can't be popped. The Navigator above this needs to
|
||||
// be popped.
|
||||
onPressed: onBack,
|
||||
child: const Text('Go back'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NestedNavigatorsPageTwo extends StatelessWidget {
|
||||
const NestedNavigatorsPageTwo({
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.grey.withBlue(180),
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
const Text('Nested Navigators Page Two'),
|
||||
const Text('A system back here will go back to Nested Navigators Page One'),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: const Text('Go back'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
// This sample demonstrates nested navigation in a bottom navigation bar.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// There are three possible tabs.
|
||||
enum _Tab {
|
||||
home,
|
||||
one,
|
||||
two,
|
||||
}
|
||||
|
||||
// Each tab has two possible pages.
|
||||
enum _TabPage {
|
||||
home,
|
||||
one,
|
||||
}
|
||||
|
||||
typedef _TabPageCallback = void Function(List<_TabPage> pages);
|
||||
|
||||
void main() => runApp(const NavigatorPopHandlerApp());
|
||||
|
||||
class NavigatorPopHandlerApp extends StatelessWidget {
|
||||
const NavigatorPopHandlerApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
initialRoute: '/home',
|
||||
routes: <String, WidgetBuilder>{
|
||||
'/home': (BuildContext context) => const _BottomNavPage(
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BottomNavPage extends StatefulWidget {
|
||||
const _BottomNavPage();
|
||||
|
||||
@override
|
||||
State<_BottomNavPage> createState() => _BottomNavPageState();
|
||||
}
|
||||
|
||||
class _BottomNavPageState extends State<_BottomNavPage> {
|
||||
_Tab _tab = _Tab.home;
|
||||
|
||||
final GlobalKey _tabHomeKey = GlobalKey();
|
||||
final GlobalKey _tabOneKey = GlobalKey();
|
||||
final GlobalKey _tabTwoKey = GlobalKey();
|
||||
|
||||
List<_TabPage> _tabHomePages = <_TabPage>[_TabPage.home];
|
||||
List<_TabPage> _tabOnePages = <_TabPage>[_TabPage.home];
|
||||
List<_TabPage> _tabTwoPages = <_TabPage>[_TabPage.home];
|
||||
|
||||
BottomNavigationBarItem _itemForPage(_Tab page) {
|
||||
switch (page) {
|
||||
case _Tab.home:
|
||||
return const BottomNavigationBarItem(
|
||||
icon: Icon(Icons.home),
|
||||
label: 'Go to Home',
|
||||
);
|
||||
case _Tab.one:
|
||||
return const BottomNavigationBarItem(
|
||||
icon: Icon(Icons.one_k),
|
||||
label: 'Go to One',
|
||||
);
|
||||
case _Tab.two:
|
||||
return const BottomNavigationBarItem(
|
||||
icon: Icon(Icons.two_k),
|
||||
label: 'Go to Two',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _getPage(_Tab page) {
|
||||
switch (page) {
|
||||
case _Tab.home:
|
||||
return _BottomNavTab(
|
||||
key: _tabHomeKey,
|
||||
title: 'Home Tab',
|
||||
color: Colors.grey,
|
||||
pages: _tabHomePages,
|
||||
onChangedPages: (List<_TabPage> pages) {
|
||||
setState(() {
|
||||
_tabHomePages = pages;
|
||||
});
|
||||
},
|
||||
);
|
||||
case _Tab.one:
|
||||
return _BottomNavTab(
|
||||
key: _tabOneKey,
|
||||
title: 'Tab One',
|
||||
color: Colors.amber,
|
||||
pages: _tabOnePages,
|
||||
onChangedPages: (List<_TabPage> pages) {
|
||||
setState(() {
|
||||
_tabOnePages = pages;
|
||||
});
|
||||
},
|
||||
);
|
||||
case _Tab.two:
|
||||
return _BottomNavTab(
|
||||
key: _tabTwoKey,
|
||||
title: 'Tab Two',
|
||||
color: Colors.blueGrey,
|
||||
pages: _tabTwoPages,
|
||||
onChangedPages: (List<_TabPage> pages) {
|
||||
setState(() {
|
||||
_tabTwoPages = pages;
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _onItemTapped(int index) {
|
||||
setState(() {
|
||||
_tab = _Tab.values.elementAt(index);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: Center(
|
||||
child: _getPage(_tab),
|
||||
),
|
||||
bottomNavigationBar: BottomNavigationBar(
|
||||
items: _Tab.values.map(_itemForPage).toList(),
|
||||
currentIndex: _Tab.values.indexOf(_tab),
|
||||
selectedItemColor: Colors.amber[800],
|
||||
onTap: _onItemTapped,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BottomNavTab extends StatefulWidget {
|
||||
const _BottomNavTab({
|
||||
super.key,
|
||||
required this.color,
|
||||
required this.onChangedPages,
|
||||
required this.pages,
|
||||
required this.title,
|
||||
});
|
||||
|
||||
final Color color;
|
||||
final _TabPageCallback onChangedPages;
|
||||
final List<_TabPage> pages;
|
||||
final String title;
|
||||
|
||||
@override
|
||||
State<_BottomNavTab> createState() => _BottomNavTabState();
|
||||
}
|
||||
|
||||
class _BottomNavTabState extends State<_BottomNavTab> {
|
||||
final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return NavigatorPopHandler(
|
||||
onPop: () {
|
||||
_navigatorKey.currentState?.maybePop();
|
||||
},
|
||||
child: Navigator(
|
||||
key: _navigatorKey,
|
||||
onPopPage: (Route<void> route, void result) {
|
||||
if (!route.didPop(null)) {
|
||||
return false;
|
||||
}
|
||||
widget.onChangedPages(<_TabPage>[
|
||||
...widget.pages,
|
||||
]..removeLast());
|
||||
return true;
|
||||
},
|
||||
pages: widget.pages.map((_TabPage page) {
|
||||
switch (page) {
|
||||
case _TabPage.home:
|
||||
return MaterialPage<void>(
|
||||
child: _LinksPage(
|
||||
title: 'Bottom nav - tab ${widget.title} - route $page',
|
||||
backgroundColor: widget.color,
|
||||
buttons: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
widget.onChangedPages(<_TabPage>[
|
||||
...widget.pages,
|
||||
_TabPage.one,
|
||||
]);
|
||||
},
|
||||
child: const Text('Go to another route in this nested Navigator'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
case _TabPage.one:
|
||||
return MaterialPage<void>(
|
||||
child: _LinksPage(
|
||||
backgroundColor: widget.color,
|
||||
title: 'Bottom nav - tab ${widget.title} - route $page',
|
||||
buttons: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
widget.onChangedPages(<_TabPage>[
|
||||
...widget.pages,
|
||||
]..removeLast());
|
||||
},
|
||||
child: const Text('Go back'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}).toList(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _LinksPage extends StatelessWidget {
|
||||
const _LinksPage ({
|
||||
required this.backgroundColor,
|
||||
this.buttons = const <Widget>[],
|
||||
required this.title,
|
||||
});
|
||||
|
||||
final Color backgroundColor;
|
||||
final List<Widget> buttons;
|
||||
final String title;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: backgroundColor,
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Text(title),
|
||||
...buttons,
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
128
examples/api/lib/widgets/pop_scope/pop_scope.0.dart
Normal file
128
examples/api/lib/widgets/pop_scope/pop_scope.0.dart
Normal file
@@ -0,0 +1,128 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
// This sample demonstrates showing a confirmation dialog before navigating
|
||||
// away from a page.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
void main() => runApp(const NavigatorPopHandlerApp());
|
||||
|
||||
class NavigatorPopHandlerApp extends StatelessWidget {
|
||||
const NavigatorPopHandlerApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
initialRoute: '/home',
|
||||
routes: <String, WidgetBuilder>{
|
||||
'/home': (BuildContext context) => const _HomePage(),
|
||||
'/two': (BuildContext context) => const _PageTwo(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HomePage extends StatefulWidget {
|
||||
const _HomePage();
|
||||
|
||||
@override
|
||||
State<_HomePage> createState() => _HomePageState();
|
||||
}
|
||||
|
||||
class _HomePageState extends State<_HomePage> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
const Text('Page One'),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pushNamed('/two');
|
||||
},
|
||||
child: const Text('Next page'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PageTwo extends StatefulWidget {
|
||||
const _PageTwo();
|
||||
|
||||
@override
|
||||
State<_PageTwo> createState() => _PageTwoState();
|
||||
}
|
||||
|
||||
class _PageTwoState extends State<_PageTwo> {
|
||||
void _showBackDialog() {
|
||||
showDialog<void>(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Are you sure?'),
|
||||
content: const Text(
|
||||
'Are you sure you want to leave this page?',
|
||||
),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
style: TextButton.styleFrom(
|
||||
textStyle: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
child: const Text('Nevermind'),
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
TextButton(
|
||||
style: TextButton.styleFrom(
|
||||
textStyle: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
child: const Text('Leave'),
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
const Text('Page Two'),
|
||||
PopScope(
|
||||
canPop: false,
|
||||
onPopInvoked: (bool didPop) {
|
||||
if (didPop) {
|
||||
return;
|
||||
}
|
||||
_showBackDialog();
|
||||
},
|
||||
child: TextButton(
|
||||
onPressed: () {
|
||||
_showBackDialog();
|
||||
},
|
||||
child: const Text('Go back'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Flutter code sample for [WillPopScope].
|
||||
|
||||
void main() => runApp(const WillPopScopeExampleApp());
|
||||
|
||||
class WillPopScopeExampleApp extends StatelessWidget {
|
||||
const WillPopScopeExampleApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const MaterialApp(
|
||||
home: WillPopScopeExample(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class WillPopScopeExample extends StatefulWidget {
|
||||
const WillPopScopeExample({super.key});
|
||||
|
||||
@override
|
||||
State<WillPopScopeExample> createState() => _WillPopScopeExampleState();
|
||||
}
|
||||
|
||||
class _WillPopScopeExampleState extends State<WillPopScopeExample> {
|
||||
bool shouldPop = true;
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return WillPopScope(
|
||||
onWillPop: () async {
|
||||
return shouldPop;
|
||||
},
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Flutter WillPopScope demo'),
|
||||
),
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
OutlinedButton(
|
||||
child: const Text('Push'),
|
||||
onPressed: () {
|
||||
Navigator.of(context).push<void>(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (BuildContext context) {
|
||||
return const WillPopScopeExample();
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
OutlinedButton(
|
||||
child: Text('shouldPop: $shouldPop'),
|
||||
onPressed: () {
|
||||
setState(
|
||||
() {
|
||||
shouldPop = !shouldPop;
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
const Text('Push to a new screen, then tap on shouldPop '
|
||||
'button to toggle its value. Press the back '
|
||||
'button in the appBar to check its behavior '
|
||||
'for different values of shouldPop'),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
37
examples/api/test/widgets/form/form.1_test.dart
Normal file
37
examples/api/test/widgets/form/form.1_test.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_api_samples/widgets/form/form.1.dart' as example;
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('Can go back when form is clean', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
const example.FormApp(),
|
||||
);
|
||||
|
||||
expect(find.text('Are you sure?'), findsNothing);
|
||||
|
||||
await tester.tap(find.text('Go back'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Are you sure?'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('Cannot go back when form is dirty', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
const example.FormApp(),
|
||||
);
|
||||
|
||||
expect(find.text('Are you sure?'), findsNothing);
|
||||
|
||||
await tester.enterText(find.byType(TextFormField), 'some new text');
|
||||
|
||||
await tester.tap(find.text('Go back'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Are you sure?'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter_api_samples/widgets/navigator_pop_handler/navigator_pop_handler.0.dart' as example;
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../navigator_utils.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('Can go back with system back gesture', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
const example.NavigatorPopHandlerApp(),
|
||||
);
|
||||
|
||||
expect(find.text('Nested Navigators Example'), findsOneWidget);
|
||||
expect(find.text('Nested Navigators Page One'), findsNothing);
|
||||
expect(find.text('Nested Navigators Page Two'), findsNothing);
|
||||
|
||||
await tester.tap(find.text('Nested Navigator route'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Nested Navigators Example'), findsNothing);
|
||||
expect(find.text('Nested Navigators Page One'), findsOneWidget);
|
||||
expect(find.text('Nested Navigators Page Two'), findsNothing);
|
||||
|
||||
await tester.tap(find.text('Go to another route in this nested Navigator'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Nested Navigators Example'), findsNothing);
|
||||
expect(find.text('Nested Navigators Page One'), findsNothing);
|
||||
expect(find.text('Nested Navigators Page Two'), findsOneWidget);
|
||||
|
||||
await simulateSystemBack();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Nested Navigators Example'), findsNothing);
|
||||
expect(find.text('Nested Navigators Page One'), findsOneWidget);
|
||||
expect(find.text('Nested Navigators Page Two'), findsNothing);
|
||||
|
||||
await simulateSystemBack();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Nested Navigators Example'), findsOneWidget);
|
||||
expect(find.text('Nested Navigators Page One'), findsNothing);
|
||||
expect(find.text('Nested Navigators Page Two'), findsNothing);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter_api_samples/widgets/navigator_pop_handler/navigator_pop_handler.1.dart' as example;
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../navigator_utils.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets("System back gesture operates on current tab's nested Navigator", (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
const example.NavigatorPopHandlerApp(),
|
||||
);
|
||||
|
||||
expect(find.text('Bottom nav - tab Home Tab - route _TabPage.home'), findsOneWidget);
|
||||
|
||||
// Go to the next route in this tab.
|
||||
await tester.tap(find.text('Go to another route in this nested Navigator'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Bottom nav - tab Home Tab - route _TabPage.one'), findsOneWidget);
|
||||
|
||||
// Go to another tab.
|
||||
await tester.tap(find.text('Go to One'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Bottom nav - tab Tab One - route _TabPage.home'), findsOneWidget);
|
||||
|
||||
// Return to the home tab. The navigation state is preserved.
|
||||
await tester.tap(find.text('Go to Home'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Bottom nav - tab Home Tab - route _TabPage.one'), findsOneWidget);
|
||||
|
||||
// A back pops the navigation stack of the current tab's nested Navigator.
|
||||
await simulateSystemBack();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Bottom nav - tab Home Tab - route _TabPage.home'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
20
examples/api/test/widgets/navigator_utils.dart
Normal file
20
examples/api/test/widgets/navigator_utils.dart
Normal file
@@ -0,0 +1,20 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
/// Simulates a system back, like a back gesture on Android.
|
||||
///
|
||||
/// Sends the same platform channel message that the engine sends when it
|
||||
/// receives a system back.
|
||||
Future<void> simulateSystemBack() {
|
||||
return TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
|
||||
'flutter/navigation',
|
||||
const JSONMessageCodec().encodeMessage(<String, dynamic>{
|
||||
'method': 'popRoute',
|
||||
}),
|
||||
(ByteData? _) {},
|
||||
);
|
||||
}
|
||||
66
examples/api/test/widgets/pop_scope/pop_scope.0_test.dart
Normal file
66
examples/api/test/widgets/pop_scope/pop_scope.0_test.dart
Normal file
@@ -0,0 +1,66 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter_api_samples/widgets/pop_scope/pop_scope.0.dart' as example;
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../navigator_utils.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('Can choose to stay on page', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
const example.NavigatorPopHandlerApp(),
|
||||
);
|
||||
|
||||
expect(find.text('Page One'), findsOneWidget);
|
||||
expect(find.text('Page Two'), findsNothing);
|
||||
expect(find.text('Are you sure?'), findsNothing);
|
||||
|
||||
await tester.tap(find.text('Next page'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Page One'), findsNothing);
|
||||
expect(find.text('Page Two'), findsOneWidget);
|
||||
expect(find.text('Are you sure?'), findsNothing);
|
||||
|
||||
await simulateSystemBack();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Page One'), findsNothing);
|
||||
expect(find.text('Page Two'), findsOneWidget);
|
||||
expect(find.text('Are you sure?'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Nevermind'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Page One'), findsNothing);
|
||||
expect(find.text('Page Two'), findsOneWidget);
|
||||
expect(find.text('Are you sure?'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('Can choose to go back', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
const example.NavigatorPopHandlerApp(),
|
||||
);
|
||||
|
||||
expect(find.text('Page One'), findsOneWidget);
|
||||
expect(find.text('Page Two'), findsNothing);
|
||||
expect(find.text('Are you sure?'), findsNothing);
|
||||
|
||||
await tester.tap(find.text('Next page'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Page One'), findsNothing);
|
||||
expect(find.text('Page Two'), findsOneWidget);
|
||||
expect(find.text('Are you sure?'), findsNothing);
|
||||
|
||||
await simulateSystemBack();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Page One'), findsNothing);
|
||||
expect(find.text('Page Two'), findsOneWidget);
|
||||
expect(find.text('Are you sure?'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Leave'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Page One'), findsOneWidget);
|
||||
expect(find.text('Page Two'), findsNothing);
|
||||
expect(find.text('Are you sure?'), findsNothing);
|
||||
});
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter_api_samples/widgets/will_pop_scope/will_pop_scope.0.dart' as example;
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('pressing shouldPop button changes shouldPop', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
const example.WillPopScopeExampleApp(),
|
||||
);
|
||||
|
||||
final Finder buttonFinder = find.text('shouldPop: true');
|
||||
expect(buttonFinder, findsOneWidget);
|
||||
await tester.tap(buttonFinder);
|
||||
await tester.pump();
|
||||
expect(find.text('shouldPop: false'), findsOneWidget);
|
||||
});
|
||||
testWidgets('pressing Push button pushes route', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
const example.WillPopScopeExampleApp(),
|
||||
);
|
||||
|
||||
final Finder buttonFinder = find.text('Push');
|
||||
expect(buttonFinder, findsOneWidget);
|
||||
expect(find.byType(example.WillPopScopeExample), findsOneWidget);
|
||||
await tester.tap(buttonFinder);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(example.WillPopScopeExample, skipOffstage: false), findsNWidgets(2));
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user