具有 url 更新和超链接支持的 Flutter Web 底部导航栏
Flutter web Bottom Navigation Bar with url updating and hyperlink support
我在网上搜索了很多年,想找到一个支持以下内容的 flutter 应用示例:
- 持久底部导航栏
- 导航器支持每个保持状态的底部导航栏项目
- Navigators 更新 URL in flutter web on navigation
- 导航器支持超链接到 flutter web 中的特定页面。例如,如果用户键入 www.myappdomain.com/#/profile they get navigated to the profile page. Or they type www.myappdomain.com/#/profile?id=123,他们将导航到用户 123.
的个人资料页面
我已经能够使用以下代码实现第 1 点和第 2 点:
import 'package:flutter/material.dart';
void main() {
runApp(BaseApp());
}
class BaseApp extends StatefulWidget {
@override
_BaseAppState createState() => _BaseAppState();
}
class _BaseAppState extends State<BaseApp> {
// define all navigation tabs for user
static List<NavigationTabModel> _navigationTabs = [
NavigationTabModel(
title: 'Home',
icon: Icons.home,
url: '/home',
navigatorKey: GlobalKey<NavigatorState>(),
),
NavigationTabModel(
title: 'Search',
icon: Icons.search,
url: '/search',
navigatorKey: GlobalKey<NavigatorState>(),
),
NavigationTabModel(
title: 'Profile',
icon: Icons.person,
url: '/profile',
navigatorKey: GlobalKey<NavigatorState>(),
),
];
// route generator used to build all material page routes
RouteGenerator _routeGenerator = RouteGenerator();
// set the current tab to the home page
int _currentIndex = 0;
void _select(int index) {
if (index == _currentIndex) {
// case 1 - if user presses on currently selected tab
// pop to first route - i.e. ensure no routes are over laid on top of the current route
_navigationTabs[_currentIndex]
.navigatorKey
.currentState
.popUntil((route) {
return route.isFirst;
});
} else {
// case 2 - user selects any other tab
// rebuild application state with the newly selected navigation tab
setState(() {
_currentIndex = index;
});
}
}
/// generate a list of navigators that will have their state persisted in an
/// indexed stack.
List<Widget> _getPersistantStack() {
return _navigationTabs.map((tab) {
return WillPopScope(
onWillPop: () async {
return !await tab.navigatorKey.currentState.maybePop();
},
child: Navigator(
key: tab.navigatorKey,
initialRoute: tab.url,
onGenerateRoute: _routeGenerator.generateRoute,
),
);
}).toList();
}
@override
Widget build(BuildContext context) {
/// ********************* HOLD POINT *********************
/// MaterialApp contains our top-level Navigator. Top level navigator is
/// required to enable navigation via urls in flutter web. Likely that this
/// section requires refractoring in some way to enable url updates from the
/// nested navigators and hyperlinking from web browsers to specific pages
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: SafeArea(
child: IndexedStack(
children: _getPersistantStack(),
index: _currentIndex,
),
),
bottomNavigationBar: BottomNavigationBar(
items: _navigationTabs.map((tab) {
return BottomNavigationBarItem(
label: tab.title,
icon: Icon(tab.icon),
);
}).toList(),
onTap: (int index) {
_select(index);
},
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
// hide titles on navigation bar
showSelectedLabels: false,
showUnselectedLabels: false,
),
),
);
}
}
class NavigationTabModel {
final String title;
final IconData icon;
final String url;
final GlobalKey<NavigatorState> navigatorKey;
NavigationTabModel({
this.title,
this.icon,
this.url,
this.navigatorKey,
});
}
class RouteGenerator {
Route<dynamic> generateRoute(RouteSettings settings) {
// Widget builder (function that returns a widget) to construct the route page
WidgetBuilder builder;
// build different route (page) based on the route passed to the navigator
switch (settings.name) {
case '/home':
builder = (BuildContext context) {
return SamplePage(name: 'home');
};
break;
case '/search':
builder = (BuildContext context) {
return SamplePage(name: 'search');
};
break;
case '/profile':
builder = (BuildContext context) {
return SamplePage(name: 'profile');
};
break;
case '/':
builder = null;
break;
default:
// If there is no such named route in the switch statement
builder = (BuildContext context) {
return SamplePage();
};
}
// prevent page being added to default '/' route
if (builder == null) {
return null;
}
return MaterialPageRoute(
builder: builder,
settings: settings,
);
}
}
class SamplePage extends StatelessWidget {
final String name;
SamplePage({
this.name,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('$name'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
RaisedButton(
child: Text('push new route'),
onPressed: () {
Navigator.of(context).pushNamed('/$name');
},
),
SizedBox(
height: 16,
),
Expanded(
child: ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return Card(
child: Text(
index.toString(),
),
);
},
),
),
],
),
),
);
}
}
但是我不知道如何更新此应用程序以实现第 3 点和第 4 点。有人知道如何实现吗?
自 2020 年 9 月 30 日起,flutter introduced Navigator 2.0。
您可以查看 link 以获得完整的教程。跳过关于 Navigator 1.0 的部分,转到 Navigator 2.0。
基本上两个主要的小部件是 RouteInformationParser
和 RouterDelegate
。
我强烈建议阅读这篇文章,了解有关路由的更多信息。
也就是说,这是他们描述的代码,您可以在网上尝试一下,看看它是否实现了您的第 3 点和第 4 点。
import 'package:flutter/material.dart';
void main() {
runApp(BooksApp());
}
class Book {
final String title;
final String author;
Book(this.title, this.author);
}
class BooksApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => _BooksAppState();
}
class _BooksAppState extends State<BooksApp> {
BookRouterDelegate _routerDelegate = BookRouterDelegate();
BookRouteInformationParser _routeInformationParser =
BookRouteInformationParser();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Books App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
class BookRouteInformationParser extends RouteInformationParser<BookRoutePath> {
@override
Future<BookRoutePath> parseRouteInformation(
RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location);
// Handle '/'
if (uri.pathSegments.length == 0) {
return BookRoutePath.home();
}
// Handle '/book/:id'
if (uri.pathSegments.length == 2) {
if (uri.pathSegments[0] != 'book') return BookRoutePath.unknown();
var remaining = uri.pathSegments[1];
var id = int.tryParse(remaining);
if (id == null) return BookRoutePath.unknown();
return BookRoutePath.details(id);
}
// Handle unknown routes
return BookRoutePath.unknown();
}
@override
RouteInformation restoreRouteInformation(BookRoutePath path) {
if (path.isUnknown) {
return RouteInformation(location: '/404');
}
if (path.isHomePage) {
return RouteInformation(location: '/');
}
if (path.isDetailsPage) {
return RouteInformation(location: '/book/${path.id}');
}
return null;
}
}
class BookRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
final GlobalKey<NavigatorState> navigatorKey;
Book _selectedBook;
bool show404 = false;
List<Book> books = [
Book('Stranger in a Strange Land', 'Robert A. Heinlein'),
Book('Foundation', 'Isaac Asimov'),
Book('Fahrenheit 451', 'Ray Bradbury'),
];
BookRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>();
BookRoutePath get currentConfiguration {
if (show404) {
return BookRoutePath.unknown();
}
return _selectedBook == null
? BookRoutePath.home()
: BookRoutePath.details(books.indexOf(_selectedBook));
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage(
key: ValueKey('BooksListPage'),
child: BooksListScreen(
books: books,
onTapped: _handleBookTapped,
),
),
if (show404)
MaterialPage(key: ValueKey('UnknownPage'), child: UnknownScreen())
else if (_selectedBook != null)
BookDetailsPage(book: _selectedBook)
],
onPopPage: (route, result) {
if (!route.didPop(result)) {
return false;
}
// Update the list of pages by setting _selectedBook to null
_selectedBook = null;
show404 = false;
notifyListeners();
return true;
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
if (path.isUnknown) {
_selectedBook = null;
show404 = true;
return;
}
if (path.isDetailsPage) {
if (path.id < 0 || path.id > books.length - 1) {
show404 = true;
return;
}
_selectedBook = books[path.id];
} else {
_selectedBook = null;
}
show404 = false;
}
void _handleBookTapped(Book book) {
_selectedBook = book;
notifyListeners();
}
}
class BookDetailsPage extends Page {
final Book book;
BookDetailsPage({
this.book,
}) : super(key: ValueKey(book));
Route createRoute(BuildContext context) {
return MaterialPageRoute(
settings: this,
builder: (BuildContext context) {
return BookDetailsScreen(book: book);
},
);
}
}
class BookRoutePath {
final int id;
final bool isUnknown;
BookRoutePath.home()
: id = null,
isUnknown = false;
BookRoutePath.details(this.id) : isUnknown = false;
BookRoutePath.unknown()
: id = null,
isUnknown = true;
bool get isHomePage => id == null;
bool get isDetailsPage => id != null;
}
class BooksListScreen extends StatelessWidget {
final List<Book> books;
final ValueChanged<Book> onTapped;
BooksListScreen({
@required this.books,
@required this.onTapped,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ListView(
children: [
for (var book in books)
ListTile(
title: Text(book.title),
subtitle: Text(book.author),
onTap: () => onTapped(book),
)
],
),
);
}
}
class BookDetailsScreen extends StatelessWidget {
final Book book;
BookDetailsScreen({
@required this.book,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (book != null) ...[
Text(book.title, style: Theme.of(context).textTheme.headline6),
Text(book.author, style: Theme.of(context).textTheme.subtitle1),
],
],
),
),
);
}
}
class UnknownScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Text('404!'),
),
);
}
}
虽然 Navigator 2.0 一开始有点吓人,但当您(主要)针对 Web 应用程序时,它是非常值得的,因为您有很多选项可以从深层恢复状态 link。
在@Lulupointu 已经 link 访问的 official introduction 中,有一个示例正是您要查找的内容(但有点隐藏在文章的最底部)。
In this gist 是针对不同选项卡使用不同导航器堆栈的工作示例,为了完整起见,我在下面 post。它适用于 Channel beta,1.23.0-18。1.pre
import 'package:flutter/material.dart';
void main() {
runApp(NestedRouterDemo());
}
class Book {
final String title;
final String author;
Book(this.title, this.author);
}
class NestedRouterDemo extends StatefulWidget {
@override
_NestedRouterDemoState createState() => _NestedRouterDemoState();
}
class _NestedRouterDemoState extends State<NestedRouterDemo> {
BookRouterDelegate _routerDelegate = BookRouterDelegate();
BookRouteInformationParser _routeInformationParser =
BookRouteInformationParser();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Books App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
class BooksAppState extends ChangeNotifier {
int _selectedIndex;
Book _selectedBook;
final List<Book> books = [
Book('Stranger in a Strange Land', 'Robert A. Heinlein'),
Book('Foundation', 'Isaac Asimov'),
Book('Fahrenheit 451', 'Ray Bradbury'),
];
BooksAppState() : _selectedIndex = 0;
int get selectedIndex => _selectedIndex;
set selectedIndex(int idx) {
_selectedIndex = idx;
notifyListeners();
}
Book get selectedBook => _selectedBook;
set selectedBook(Book book) {
_selectedBook = book;
notifyListeners();
}
int getSelectedBookById() {
if (!books.contains(_selectedBook)) return 0;
return books.indexOf(_selectedBook);
}
void setSelectedBookById(int id) {
if (id < 0 || id > books.length - 1) {
return;
}
_selectedBook = books[id];
notifyListeners();
}
}
class BookRouteInformationParser extends RouteInformationParser<BookRoutePath> {
@override
Future<BookRoutePath> parseRouteInformation(
RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location);
if (uri.pathSegments.isNotEmpty && uri.pathSegments.first == 'settings') {
return BooksSettingsPath();
} else {
if (uri.pathSegments.length >= 2) {
if (uri.pathSegments[0] == 'book') {
return BooksDetailsPath(int.tryParse(uri.pathSegments[1]));
}
}
return BooksListPath();
}
}
@override
RouteInformation restoreRouteInformation(BookRoutePath configuration) {
if (configuration is BooksListPath) {
return RouteInformation(location: '/home');
}
if (configuration is BooksSettingsPath) {
return RouteInformation(location: '/settings');
}
if (configuration is BooksDetailsPath) {
return RouteInformation(location: '/book/${configuration.id}');
}
return null;
}
}
class BookRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
final GlobalKey<NavigatorState> navigatorKey;
BooksAppState appState = BooksAppState();
BookRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
appState.addListener(notifyListeners);
}
@override
BookRoutePath get currentConfiguration {
if (appState.selectedIndex == 1) {
return BooksSettingsPath();
} else {
if (appState.selectedBook == null) {
return BooksListPath();
} else {
return BooksDetailsPath(appState.getSelectedBookById());
}
}
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage(
child: AppShell(appState: appState),
),
],
onPopPage: (route, result) {
if (!route.didPop(result)) {
return false;
}
if (appState.selectedBook != null) {
appState.selectedBook = null;
}
notifyListeners();
return true;
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
if (path is BooksListPath) {
appState.selectedIndex = 0;
appState.selectedBook = null;
} else if (path is BooksSettingsPath) {
appState.selectedIndex = 1;
} else if (path is BooksDetailsPath) {
appState.selectedIndex = 0;
appState.setSelectedBookById(path.id);
}
}
}
// Routes
abstract class BookRoutePath {}
class BooksListPath extends BookRoutePath {}
class BooksSettingsPath extends BookRoutePath {}
class BooksDetailsPath extends BookRoutePath {
final int id;
BooksDetailsPath(this.id);
}
// Widget that contains the AdaptiveNavigationScaffold
class AppShell extends StatefulWidget {
final BooksAppState appState;
AppShell({
@required this.appState,
});
@override
_AppShellState createState() => _AppShellState();
}
class _AppShellState extends State<AppShell> {
InnerRouterDelegate _routerDelegate;
ChildBackButtonDispatcher _backButtonDispatcher;
void initState() {
super.initState();
_routerDelegate = InnerRouterDelegate(widget.appState);
}
@override
void didUpdateWidget(covariant AppShell oldWidget) {
super.didUpdateWidget(oldWidget);
_routerDelegate.appState = widget.appState;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Defer back button dispatching to the child router
_backButtonDispatcher = Router.of(context)
.backButtonDispatcher
.createChildBackButtonDispatcher();
}
@override
Widget build(BuildContext context) {
var appState = widget.appState;
// Claim priority, If there are parallel sub router, you will need
// to pick which one should take priority;
_backButtonDispatcher.takePriority();
return Scaffold(
appBar: AppBar(),
body: Router(
routerDelegate: _routerDelegate,
backButtonDispatcher: _backButtonDispatcher,
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: 'Settings'),
],
currentIndex: appState.selectedIndex,
onTap: (newIndex) {
appState.selectedIndex = newIndex;
},
),
);
}
}
class InnerRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
BooksAppState get appState => _appState;
BooksAppState _appState;
set appState(BooksAppState value) {
if (value == _appState) {
return;
}
_appState = value;
notifyListeners();
}
InnerRouterDelegate(this._appState);
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
if (appState.selectedIndex == 0) ...[
FadeAnimationPage(
child: BooksListScreen(
books: appState.books,
onTapped: _handleBookTapped,
),
key: ValueKey('BooksListPage'),
),
if (appState.selectedBook != null)
MaterialPage(
key: ValueKey(appState.selectedBook),
child: BookDetailsScreen(book: appState.selectedBook),
),
] else
FadeAnimationPage(
child: SettingsScreen(),
key: ValueKey('SettingsPage'),
),
],
onPopPage: (route, result) {
appState.selectedBook = null;
notifyListeners();
return route.didPop(result);
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
// This is not required for inner router delegate because it does not
// parse route
assert(false);
}
void _handleBookTapped(Book book) {
appState.selectedBook = book;
notifyListeners();
}
}
class FadeAnimationPage extends Page {
final Widget child;
FadeAnimationPage({Key key, this.child}) : super(key: key);
Route createRoute(BuildContext context) {
return PageRouteBuilder(
settings: this,
pageBuilder: (context, animation, animation2) {
var curveTween = CurveTween(curve: Curves.easeIn);
return FadeTransition(
opacity: animation.drive(curveTween),
child: child,
);
},
);
}
}
// Screens
class BooksListScreen extends StatelessWidget {
final List<Book> books;
final ValueChanged<Book> onTapped;
BooksListScreen({
@required this.books,
@required this.onTapped,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
for (var book in books)
ListTile(
title: Text(book.title),
subtitle: Text(book.author),
onTap: () => onTapped(book),
)
],
),
);
}
}
class BookDetailsScreen extends StatelessWidget {
final Book book;
BookDetailsScreen({
@required this.book,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Back'),
),
if (book != null) ...[
Text(book.title, style: Theme.of(context).textTheme.headline6),
Text(book.author, style: Theme.of(context).textTheme.subtitle1),
],
],
),
),
);
}
}
class SettingsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Settings screen'),
),
);
}
}
如果您希望主页导航按钮 link 到主页并且不保持状态,则必须将 set selectedIndex 替换为:
set selectedIndex(int idx) {
_selectedIndex = idx;
if (_selectedIndex == 1) {
// Remove this line if you want to keep the selected book when navigating
// between "settings" and "home" which book was selected when Settings is
// tapped.
selectedBook = null;
}
notifyListeners();
}
您可能想看看在编写自己的 RouteInformationParser 时如何提取查询参数:
Parsing a URI to extract query parameters, with Dart
这是您可能想要了解 Navigator 2.0 的另一个示例:https://github.com/flutter/flutter/pull/63424
来自此 gist 的工作底部导航与 flutter sdk >= 2.12
兼容
import 'package:flutter/material.dart';
void main() {
runApp(NestedRouterDemo());
}
class Book {
final String title;
final String author;
Book(this.title, this.author);
}
class NestedRouterDemo extends StatefulWidget {
@override
_NestedRouterDemoState createState() => _NestedRouterDemoState();
}
class _NestedRouterDemoState extends State<NestedRouterDemo> {
BookRouterDelegate _routerDelegate = BookRouterDelegate();
BookRouteInformationParser _routeInformationParser = BookRouteInformationParser();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Books App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
class BooksAppState extends ChangeNotifier {
int _selectedIndex;
Book? _selectedBook;
final List<Book> books = [
Book('Stranger in a Strange Land', 'Robert A. Heinlein'),
Book('Foundation', 'Isaac Asimov'),
Book('Fahrenheit 451', 'Ray Bradbury'),
];
BooksAppState() : _selectedIndex = 0;
int get selectedIndex => _selectedIndex;
set selectedIndex(int idx) {
_selectedIndex = idx;
notifyListeners();
}
Book? get selectedBook => _selectedBook;
set selectedBook(Book? book) {
_selectedBook = book;
notifyListeners();
}
int? getSelectedBookById() {
if (_selectedBook == null || !books.contains(_selectedBook)) return null;
return books.indexOf(_selectedBook!);
}
void setSelectedBookById(int id) {
if (id < 0 || id > books.length - 1) {
return;
}
_selectedBook = books[id];
notifyListeners();
}
}
class BookRouteInformationParser extends RouteInformationParser<BookRoutePath> {
@override
Future<BookRoutePath> parseRouteInformation(RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location ?? '');
if (uri.pathSegments.isNotEmpty && uri.pathSegments.first == 'settings') {
return BooksSettingsPath();
} else {
if (uri.pathSegments.length >= 2) {
if (uri.pathSegments[0] == 'book') {
return BooksDetailsPath(int.tryParse(uri.pathSegments[1]));
}
}
return BooksListPath();
}
}
@override
RouteInformation restoreRouteInformation(BookRoutePath configuration) {
if (configuration is BooksListPath) {
return RouteInformation(location: '/home');
}
if (configuration is BooksSettingsPath) {
return RouteInformation(location: '/settings');
}
if (configuration is BooksDetailsPath) {
return RouteInformation(location: '/book/${configuration.id}');
}
return RouteInformation();
}
}
class BookRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
final GlobalKey<NavigatorState> navigatorKey;
BooksAppState appState = BooksAppState();
BookRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
appState.addListener(notifyListeners);
}
BookRoutePath get currentConfiguration {
if (appState.selectedIndex == 1) {
return BooksSettingsPath();
} else {
if (appState.selectedBook == null) {
return BooksListPath();
} else {
return BooksDetailsPath(appState.getSelectedBookById());
}
}
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage(
child: AppShell(appState: appState),
),
],
onPopPage: (route, result) {
if (!route.didPop(result)) {
return false;
}
if (appState.selectedBook != null) {
appState.selectedBook = null;
}
notifyListeners();
return true;
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
if (path is BooksListPath) {
appState.selectedIndex = 0;
appState.selectedBook = null;
} else if (path is BooksSettingsPath) {
appState.selectedIndex = 1;
} else if (path is BooksDetailsPath && path.id != null) {
appState.setSelectedBookById(path.id!);
}
}
}
// Routes
abstract class BookRoutePath {}
class BooksListPath extends BookRoutePath {}
class BooksSettingsPath extends BookRoutePath {}
class BooksDetailsPath extends BookRoutePath {
final int? id;
BooksDetailsPath(this.id);
}
// Widget that contains the AdaptiveNavigationScaffold
class AppShell extends StatefulWidget {
final BooksAppState appState;
AppShell({
required this.appState,
});
@override
_AppShellState createState() => _AppShellState();
}
class _AppShellState extends State<AppShell> {
late InnerRouterDelegate _routerDelegate;
late ChildBackButtonDispatcher _backButtonDispatcher;
void initState() {
super.initState();
_routerDelegate = InnerRouterDelegate(widget.appState);
}
@override
void didUpdateWidget(covariant AppShell oldWidget) {
super.didUpdateWidget(oldWidget);
_routerDelegate.appState = widget.appState;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Defer back button dispatching to the child router
_backButtonDispatcher = Router.of(context).backButtonDispatcher!.createChildBackButtonDispatcher();
}
@override
Widget build(BuildContext context) {
var appState = widget.appState;
// Claim priority, If there are parallel sub router, you will need
// to pick which one should take priority;
_backButtonDispatcher.takePriority();
return Scaffold(
appBar: AppBar(),
body: Router(
routerDelegate: _routerDelegate,
backButtonDispatcher: _backButtonDispatcher,
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.settings), label: 'Settings'),
],
currentIndex: appState.selectedIndex,
onTap: (newIndex) {
appState.selectedIndex = newIndex;
},
),
);
}
}
class InnerRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
BooksAppState get appState => _appState;
BooksAppState _appState;
set appState(BooksAppState value) {
if (value == _appState) {
return;
}
_appState = value;
notifyListeners();
}
InnerRouterDelegate(this._appState);
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
if (appState.selectedIndex == 0) ...[
FadeAnimationPage(
child: BooksListScreen(
books: appState.books,
onTapped: _handleBookTapped,
),
key: ValueKey('BooksListPage'),
),
if (appState.selectedBook != null)
MaterialPage(
key: ValueKey(appState.selectedBook),
child: BookDetailsScreen(book: appState.selectedBook!),
),
] else
FadeAnimationPage(
child: SettingsScreen(),
key: ValueKey('SettingsPage'),
),
],
onPopPage: (route, result) {
appState.selectedBook = null;
notifyListeners();
return route.didPop(result);
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
// This is not required for inner router delegate because it does not
// parse route
assert(false);
}
void _handleBookTapped(Book book) {
appState.selectedBook = book;
notifyListeners();
}
}
class FadeAnimationPage extends Page {
final Widget child;
FadeAnimationPage({required LocalKey key, required this.child}) : super(key: key);
Route createRoute(BuildContext context) {
return PageRouteBuilder(
settings: this,
pageBuilder: (context, animation, animation2) {
var curveTween = CurveTween(curve: Curves.easeIn);
return FadeTransition(
opacity: animation.drive(curveTween),
child: child,
);
},
);
}
}
// Screens
class BooksListScreen extends StatelessWidget {
final List<Book> books;
final ValueChanged<Book> onTapped;
BooksListScreen({
required this.books,
required this.onTapped,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
for (var book in books)
ListTile(
title: Text(book.title),
subtitle: Text(book.author),
onTap: () => onTapped(book),
)
],
),
);
}
}
class BookDetailsScreen extends StatelessWidget {
final Book book;
BookDetailsScreen({
required this.book,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Back'),
),
Text(book.title, style: Theme.of(context).textTheme.headline6),
Text(book.author, style: Theme.of(context).textTheme.subtitle1),
],
),
),
);
}
}
class SettingsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Settings screen'),
),
);
}
}
我一直在寻找这个问题的答案太久了。我在一个我正在从事的项目上进行了 2 周和 13 次迭代,但我仍然对我拥有的许多解决方案中的任何一个都不满意 seen/tried 因为他们中的每一个都有至少一个我已经结束的主要妥协努力学习。我想我现在已经花了足够多的时间在这上面,可以说 flutter 还没有针对这个用例进行裁剪(不是优雅或简单,也不会破坏其他 flutter 功能)。它们“支持”网络,但目前,它们并未针对网络进行优化,而且很难创建模仿网络行为的应用程序。然而,这并不奇怪,因为他们基本上在 Flutter 2022 Strategy:
中声明自己
Flutter shipped the first stable release of web support in 2021, and
it remains too early to predict its ultimate success. Yet the web
developer market is huge (10m+) and Flutter offers something
distinctive for this audience compared to traditional DOM-based
frameworks. As new technologies like CanvasKit, WebGPU, AOM, and
WebAssembly with GC become available, Flutter is in a unique position
of being able to target web apps designed for this new web generation.
Its layered approach is well suited for targeting Canvas and WebGPU;
Dart compiles to highly-optimized JavaScript today and will support
WebAssembly in the future; and our consistent, Flutter's approachable
API is a notable contrast to the complex “batteries not included” web
ecosystem. Even if our role in the immediate future is a niche one,
the web ecosystem is large enough that their niche is our growth
opportunity.
然而,flutters cross-platform 功能可不是闹着玩的,因此我什至不厌其烦地花费大量时间和精力来尝试找到解决方案,而这些事情本可以用不到 10 分钟的时间来完成使用我的网络背景。我相信很多其他人都是这种情况,所以这里是下面答案的更新和改进版本,它适用于最新版本的 flutter 和 null safety,并且还使用 built-in 后退按钮而不是自定义按钮实现其他答案使用:
import 'package:flutter/material.dart';
void main() {
runApp(const NestedRouterDemo());
}
class Book {
final String title;
final String author;
Book(this.title, this.author);
}
class NestedRouterDemo extends StatefulWidget {
const NestedRouterDemo({Key? key}) : super(key: key);
@override
_NestedRouterDemoState createState() => _NestedRouterDemoState();
}
class _NestedRouterDemoState extends State<NestedRouterDemo> {
final BookRouterDelegate _routerDelegate = BookRouterDelegate();
final BookRouteInformationParser _routeInformationParser =
BookRouteInformationParser();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Books App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
class BooksAppState extends ChangeNotifier {
int _selectedIndex;
Book? _selectedBook;
final List<Book> books = [
Book('Stranger in a Strange Land', 'Robert A. Heinlein'),
Book('Foundation', 'Isaac Asimov'),
Book('Fahrenheit 451', 'Ray Bradbury'),
];
BooksAppState() : _selectedIndex = 0;
int get selectedIndex => _selectedIndex;
set selectedIndex(int idx) {
_selectedIndex = idx;
// uncomment this line if you dont want to keep the selected book when navigating
// between "settings" and "home" although if your doing this you should only really need 1 nested navigator for the whole app
// if (_selectedIndex == 1) {
// selectedBook = null;
// }
notifyListeners();
}
Book? get selectedBook => _selectedBook;
set selectedBook(Book? book) {
_selectedBook = book;
notifyListeners();
}
int getSelectedBookById() {
if (!books.contains(_selectedBook)) return 0;
return books.indexOf(_selectedBook!);
}
void setSelectedBookById(int id) {
if (id < 0 || id > books.length - 1) {
return;
}
_selectedBook = books[id];
notifyListeners();
}
}
class BookRouteInformationParser extends RouteInformationParser<BookRoutePath> {
@override
Future<BookRoutePath> parseRouteInformation(
RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location!);
if (uri.pathSegments.isNotEmpty && uri.pathSegments.first == 'settings') {
return BooksSettingsPath();
} else {
if (uri.pathSegments.length >= 2) {
if (uri.pathSegments[0] == 'book') {
return BooksDetailsPath(int.tryParse(uri.pathSegments[1])!);
}
}
return BooksListPath();
}
}
@override
RouteInformation? restoreRouteInformation(BookRoutePath configuration) {
if (configuration is BooksListPath) {
return const RouteInformation(location: '/home');
}
if (configuration is BooksSettingsPath) {
return const RouteInformation(location: '/settings');
}
if (configuration is BooksDetailsPath) {
return RouteInformation(location: '/book/${configuration.id}');
}
return null;
}
}
class BookRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
@override
final GlobalKey<NavigatorState> navigatorKey;
BooksAppState appState = BooksAppState();
BookRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
appState.addListener(notifyListeners);
}
@override
BookRoutePath get currentConfiguration {
if (appState.selectedIndex == 1) {
return BooksSettingsPath();
} else {
if (appState.selectedBook == null) {
return BooksListPath();
} else {
return BooksDetailsPath(appState.getSelectedBookById());
}
}
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage(
child: AppShell(appState: appState),
),
],
onPopPage: (route, result) {
if (!route.didPop(result)) {
return false;
}
if (appState.selectedBook != null) {
appState.selectedBook = null;
}
notifyListeners();
return true;
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath configuration) async {
if (configuration is BooksListPath) {
appState.selectedIndex = 0;
appState.selectedBook = null;
} else if (configuration is BooksSettingsPath) {
appState.selectedIndex = 1;
} else if (configuration is BooksDetailsPath) {
appState.selectedIndex = 0;
appState.setSelectedBookById(configuration.id);
}
}
}
// Routes
abstract class BookRoutePath {}
class BooksListPath extends BookRoutePath {}
class BooksSettingsPath extends BookRoutePath {}
class BooksDetailsPath extends BookRoutePath {
final int id;
BooksDetailsPath(this.id);
}
// Widget that contains the AdaptiveNavigationScaffold
class AppShell extends StatefulWidget {
final BooksAppState appState;
const AppShell({
Key? key,
required this.appState,
}) : super(key: key);
@override
_AppShellState createState() => _AppShellState();
}
class _AppShellState extends State<AppShell> {
late InnerRouterDelegate _routerDelegate;
late ChildBackButtonDispatcher _backButtonDispatcher;
@override
void initState() {
super.initState();
_routerDelegate = InnerRouterDelegate(widget.appState);
}
@override
void didUpdateWidget(covariant AppShell oldWidget) {
super.didUpdateWidget(oldWidget);
_routerDelegate.appState = widget.appState;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Defer back button dispatching to the child router
_backButtonDispatcher = Router.of(context)
.backButtonDispatcher!
.createChildBackButtonDispatcher();
}
@override
Widget build(BuildContext context) {
var appState = widget.appState;
// Claim priority, If there are parallel sub router, you will need
// to pick which one should take priority;
_backButtonDispatcher.takePriority();
return Scaffold(
body: SizedBox(
height: double.infinity,
width: double.infinity,
child: Router(
routerDelegate: _routerDelegate,
backButtonDispatcher: _backButtonDispatcher,
),
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: 'Settings'),
],
currentIndex: appState.selectedIndex,
onTap: (newIndex) {
appState.selectedIndex = newIndex;
},
),
);
}
}
class InnerRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
@override
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
BooksAppState get appState => _appState;
BooksAppState _appState;
set appState(BooksAppState value) {
if (value == _appState) {
return;
}
_appState = value;
notifyListeners();
}
InnerRouterDelegate(this._appState);
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
if (appState.selectedIndex == 0) ...[
FadeAnimationPage(
child: BooksListScreen(
books: appState.books,
onTapped: _handleBookTapped,
),
key: const ValueKey('BooksListPage'),
),
if (appState.selectedBook != null)
MaterialPage(
key: ValueKey(appState.selectedBook),
child: BookDetailsScreen(book: appState.selectedBook!),
),
] else
const FadeAnimationPage(
child: SettingsScreen(),
key: ValueKey('SettingsPage'),
),
],
onPopPage: (route, result) {
appState.selectedBook = null;
notifyListeners();
return route.didPop(result);
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
// This is not required for inner router delegate because it does not
// parse route
assert(false);
}
void _handleBookTapped(Book book) {
appState.selectedBook = book;
notifyListeners();
}
}
class FadeAnimationPage extends Page {
final Widget child;
const FadeAnimationPage({required LocalKey key, required this.child})
: super(key: key);
@override
Route createRoute(BuildContext context) {
return PageRouteBuilder(
settings: this,
pageBuilder: (context, animation, animation2) {
var curveTween = CurveTween(curve: Curves.easeIn);
return FadeTransition(
opacity: animation.drive(curveTween),
child: child,
);
},
);
}
}
// Screens
class BooksListScreen extends StatelessWidget {
final List<Book> books;
final ValueChanged<Book> onTapped;
const BooksListScreen({
Key? key,
required this.books,
required this.onTapped,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Books'),
),
body: ListView(
children: [
for (var book in books)
ListTile(
title: Text(book.title),
subtitle: Text(book.author),
onTap: () => onTapped(book),
)
],
),
);
}
}
class BookDetailsScreen extends StatelessWidget {
final Book book;
const BookDetailsScreen({
Key? key,
required this.book,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(book.title),
),
body: Center(
child: SizedBox(
width: 200,
child: ListTile(
title: Text(book.title),
subtitle: Text(book.author),
),
),
),
);
}
}
class SettingsScreen extends StatelessWidget {
const SettingsScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Settings'),
),
body: const Center(
child: Text('Settings screen'),
),
);
}
}
还有一些额外的事情值得一提:
- 上面的这个例子似乎破坏了页面转换和英雄动画(因此使用 'FadeAnimationPage' 的原因)。我找到了这个 Flutter Navigator 2.0 for mobile dev: Nested navigators basics,它声称可以解决这个问题,但是我在这个例子中尝试实现它却没有成功
- 我只使用了这个例子,因为它是以前的答案并且被破坏了,但我认为这是矫枉过正的。我认为实现此类功能的最常见用例是尝试为仍然适用于路由的网络创建持久导航。为此,整个应用程序只需要一个嵌套导航器。我还读到嵌套导航器也会对性能产生重大影响,所以我实际上建议不要使用超过 1 个导航器,除非你有非常具体的原因。
- 最后,这个例子太复杂了,flutter 团队知道这一点。他们甚至开始 Flutter User Experience Research (UXR) to try and solve this however if I'm honest there is not as much activity on this as I would like to see. That is why I would recommend using a package such as GoRouter. They have a very well documented nested navigation tutorial here
我在网上搜索了很多年,想找到一个支持以下内容的 flutter 应用示例:
- 持久底部导航栏
- 导航器支持每个保持状态的底部导航栏项目
- Navigators 更新 URL in flutter web on navigation
- 导航器支持超链接到 flutter web 中的特定页面。例如,如果用户键入 www.myappdomain.com/#/profile they get navigated to the profile page. Or they type www.myappdomain.com/#/profile?id=123,他们将导航到用户 123. 的个人资料页面
我已经能够使用以下代码实现第 1 点和第 2 点:
import 'package:flutter/material.dart';
void main() {
runApp(BaseApp());
}
class BaseApp extends StatefulWidget {
@override
_BaseAppState createState() => _BaseAppState();
}
class _BaseAppState extends State<BaseApp> {
// define all navigation tabs for user
static List<NavigationTabModel> _navigationTabs = [
NavigationTabModel(
title: 'Home',
icon: Icons.home,
url: '/home',
navigatorKey: GlobalKey<NavigatorState>(),
),
NavigationTabModel(
title: 'Search',
icon: Icons.search,
url: '/search',
navigatorKey: GlobalKey<NavigatorState>(),
),
NavigationTabModel(
title: 'Profile',
icon: Icons.person,
url: '/profile',
navigatorKey: GlobalKey<NavigatorState>(),
),
];
// route generator used to build all material page routes
RouteGenerator _routeGenerator = RouteGenerator();
// set the current tab to the home page
int _currentIndex = 0;
void _select(int index) {
if (index == _currentIndex) {
// case 1 - if user presses on currently selected tab
// pop to first route - i.e. ensure no routes are over laid on top of the current route
_navigationTabs[_currentIndex]
.navigatorKey
.currentState
.popUntil((route) {
return route.isFirst;
});
} else {
// case 2 - user selects any other tab
// rebuild application state with the newly selected navigation tab
setState(() {
_currentIndex = index;
});
}
}
/// generate a list of navigators that will have their state persisted in an
/// indexed stack.
List<Widget> _getPersistantStack() {
return _navigationTabs.map((tab) {
return WillPopScope(
onWillPop: () async {
return !await tab.navigatorKey.currentState.maybePop();
},
child: Navigator(
key: tab.navigatorKey,
initialRoute: tab.url,
onGenerateRoute: _routeGenerator.generateRoute,
),
);
}).toList();
}
@override
Widget build(BuildContext context) {
/// ********************* HOLD POINT *********************
/// MaterialApp contains our top-level Navigator. Top level navigator is
/// required to enable navigation via urls in flutter web. Likely that this
/// section requires refractoring in some way to enable url updates from the
/// nested navigators and hyperlinking from web browsers to specific pages
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: SafeArea(
child: IndexedStack(
children: _getPersistantStack(),
index: _currentIndex,
),
),
bottomNavigationBar: BottomNavigationBar(
items: _navigationTabs.map((tab) {
return BottomNavigationBarItem(
label: tab.title,
icon: Icon(tab.icon),
);
}).toList(),
onTap: (int index) {
_select(index);
},
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
// hide titles on navigation bar
showSelectedLabels: false,
showUnselectedLabels: false,
),
),
);
}
}
class NavigationTabModel {
final String title;
final IconData icon;
final String url;
final GlobalKey<NavigatorState> navigatorKey;
NavigationTabModel({
this.title,
this.icon,
this.url,
this.navigatorKey,
});
}
class RouteGenerator {
Route<dynamic> generateRoute(RouteSettings settings) {
// Widget builder (function that returns a widget) to construct the route page
WidgetBuilder builder;
// build different route (page) based on the route passed to the navigator
switch (settings.name) {
case '/home':
builder = (BuildContext context) {
return SamplePage(name: 'home');
};
break;
case '/search':
builder = (BuildContext context) {
return SamplePage(name: 'search');
};
break;
case '/profile':
builder = (BuildContext context) {
return SamplePage(name: 'profile');
};
break;
case '/':
builder = null;
break;
default:
// If there is no such named route in the switch statement
builder = (BuildContext context) {
return SamplePage();
};
}
// prevent page being added to default '/' route
if (builder == null) {
return null;
}
return MaterialPageRoute(
builder: builder,
settings: settings,
);
}
}
class SamplePage extends StatelessWidget {
final String name;
SamplePage({
this.name,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('$name'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
RaisedButton(
child: Text('push new route'),
onPressed: () {
Navigator.of(context).pushNamed('/$name');
},
),
SizedBox(
height: 16,
),
Expanded(
child: ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return Card(
child: Text(
index.toString(),
),
);
},
),
),
],
),
),
);
}
}
但是我不知道如何更新此应用程序以实现第 3 点和第 4 点。有人知道如何实现吗?
自 2020 年 9 月 30 日起,flutter introduced Navigator 2.0。
您可以查看 link 以获得完整的教程。跳过关于 Navigator 1.0 的部分,转到 Navigator 2.0。
基本上两个主要的小部件是 RouteInformationParser
和 RouterDelegate
。
我强烈建议阅读这篇文章,了解有关路由的更多信息。
也就是说,这是他们描述的代码,您可以在网上尝试一下,看看它是否实现了您的第 3 点和第 4 点。
import 'package:flutter/material.dart';
void main() {
runApp(BooksApp());
}
class Book {
final String title;
final String author;
Book(this.title, this.author);
}
class BooksApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => _BooksAppState();
}
class _BooksAppState extends State<BooksApp> {
BookRouterDelegate _routerDelegate = BookRouterDelegate();
BookRouteInformationParser _routeInformationParser =
BookRouteInformationParser();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Books App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
class BookRouteInformationParser extends RouteInformationParser<BookRoutePath> {
@override
Future<BookRoutePath> parseRouteInformation(
RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location);
// Handle '/'
if (uri.pathSegments.length == 0) {
return BookRoutePath.home();
}
// Handle '/book/:id'
if (uri.pathSegments.length == 2) {
if (uri.pathSegments[0] != 'book') return BookRoutePath.unknown();
var remaining = uri.pathSegments[1];
var id = int.tryParse(remaining);
if (id == null) return BookRoutePath.unknown();
return BookRoutePath.details(id);
}
// Handle unknown routes
return BookRoutePath.unknown();
}
@override
RouteInformation restoreRouteInformation(BookRoutePath path) {
if (path.isUnknown) {
return RouteInformation(location: '/404');
}
if (path.isHomePage) {
return RouteInformation(location: '/');
}
if (path.isDetailsPage) {
return RouteInformation(location: '/book/${path.id}');
}
return null;
}
}
class BookRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
final GlobalKey<NavigatorState> navigatorKey;
Book _selectedBook;
bool show404 = false;
List<Book> books = [
Book('Stranger in a Strange Land', 'Robert A. Heinlein'),
Book('Foundation', 'Isaac Asimov'),
Book('Fahrenheit 451', 'Ray Bradbury'),
];
BookRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>();
BookRoutePath get currentConfiguration {
if (show404) {
return BookRoutePath.unknown();
}
return _selectedBook == null
? BookRoutePath.home()
: BookRoutePath.details(books.indexOf(_selectedBook));
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage(
key: ValueKey('BooksListPage'),
child: BooksListScreen(
books: books,
onTapped: _handleBookTapped,
),
),
if (show404)
MaterialPage(key: ValueKey('UnknownPage'), child: UnknownScreen())
else if (_selectedBook != null)
BookDetailsPage(book: _selectedBook)
],
onPopPage: (route, result) {
if (!route.didPop(result)) {
return false;
}
// Update the list of pages by setting _selectedBook to null
_selectedBook = null;
show404 = false;
notifyListeners();
return true;
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
if (path.isUnknown) {
_selectedBook = null;
show404 = true;
return;
}
if (path.isDetailsPage) {
if (path.id < 0 || path.id > books.length - 1) {
show404 = true;
return;
}
_selectedBook = books[path.id];
} else {
_selectedBook = null;
}
show404 = false;
}
void _handleBookTapped(Book book) {
_selectedBook = book;
notifyListeners();
}
}
class BookDetailsPage extends Page {
final Book book;
BookDetailsPage({
this.book,
}) : super(key: ValueKey(book));
Route createRoute(BuildContext context) {
return MaterialPageRoute(
settings: this,
builder: (BuildContext context) {
return BookDetailsScreen(book: book);
},
);
}
}
class BookRoutePath {
final int id;
final bool isUnknown;
BookRoutePath.home()
: id = null,
isUnknown = false;
BookRoutePath.details(this.id) : isUnknown = false;
BookRoutePath.unknown()
: id = null,
isUnknown = true;
bool get isHomePage => id == null;
bool get isDetailsPage => id != null;
}
class BooksListScreen extends StatelessWidget {
final List<Book> books;
final ValueChanged<Book> onTapped;
BooksListScreen({
@required this.books,
@required this.onTapped,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ListView(
children: [
for (var book in books)
ListTile(
title: Text(book.title),
subtitle: Text(book.author),
onTap: () => onTapped(book),
)
],
),
);
}
}
class BookDetailsScreen extends StatelessWidget {
final Book book;
BookDetailsScreen({
@required this.book,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (book != null) ...[
Text(book.title, style: Theme.of(context).textTheme.headline6),
Text(book.author, style: Theme.of(context).textTheme.subtitle1),
],
],
),
),
);
}
}
class UnknownScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Text('404!'),
),
);
}
}
虽然 Navigator 2.0 一开始有点吓人,但当您(主要)针对 Web 应用程序时,它是非常值得的,因为您有很多选项可以从深层恢复状态 link。
在@Lulupointu 已经 link 访问的 official introduction 中,有一个示例正是您要查找的内容(但有点隐藏在文章的最底部)。
In this gist 是针对不同选项卡使用不同导航器堆栈的工作示例,为了完整起见,我在下面 post。它适用于 Channel beta,1.23.0-18。1.pre
import 'package:flutter/material.dart';
void main() {
runApp(NestedRouterDemo());
}
class Book {
final String title;
final String author;
Book(this.title, this.author);
}
class NestedRouterDemo extends StatefulWidget {
@override
_NestedRouterDemoState createState() => _NestedRouterDemoState();
}
class _NestedRouterDemoState extends State<NestedRouterDemo> {
BookRouterDelegate _routerDelegate = BookRouterDelegate();
BookRouteInformationParser _routeInformationParser =
BookRouteInformationParser();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Books App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
class BooksAppState extends ChangeNotifier {
int _selectedIndex;
Book _selectedBook;
final List<Book> books = [
Book('Stranger in a Strange Land', 'Robert A. Heinlein'),
Book('Foundation', 'Isaac Asimov'),
Book('Fahrenheit 451', 'Ray Bradbury'),
];
BooksAppState() : _selectedIndex = 0;
int get selectedIndex => _selectedIndex;
set selectedIndex(int idx) {
_selectedIndex = idx;
notifyListeners();
}
Book get selectedBook => _selectedBook;
set selectedBook(Book book) {
_selectedBook = book;
notifyListeners();
}
int getSelectedBookById() {
if (!books.contains(_selectedBook)) return 0;
return books.indexOf(_selectedBook);
}
void setSelectedBookById(int id) {
if (id < 0 || id > books.length - 1) {
return;
}
_selectedBook = books[id];
notifyListeners();
}
}
class BookRouteInformationParser extends RouteInformationParser<BookRoutePath> {
@override
Future<BookRoutePath> parseRouteInformation(
RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location);
if (uri.pathSegments.isNotEmpty && uri.pathSegments.first == 'settings') {
return BooksSettingsPath();
} else {
if (uri.pathSegments.length >= 2) {
if (uri.pathSegments[0] == 'book') {
return BooksDetailsPath(int.tryParse(uri.pathSegments[1]));
}
}
return BooksListPath();
}
}
@override
RouteInformation restoreRouteInformation(BookRoutePath configuration) {
if (configuration is BooksListPath) {
return RouteInformation(location: '/home');
}
if (configuration is BooksSettingsPath) {
return RouteInformation(location: '/settings');
}
if (configuration is BooksDetailsPath) {
return RouteInformation(location: '/book/${configuration.id}');
}
return null;
}
}
class BookRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
final GlobalKey<NavigatorState> navigatorKey;
BooksAppState appState = BooksAppState();
BookRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
appState.addListener(notifyListeners);
}
@override
BookRoutePath get currentConfiguration {
if (appState.selectedIndex == 1) {
return BooksSettingsPath();
} else {
if (appState.selectedBook == null) {
return BooksListPath();
} else {
return BooksDetailsPath(appState.getSelectedBookById());
}
}
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage(
child: AppShell(appState: appState),
),
],
onPopPage: (route, result) {
if (!route.didPop(result)) {
return false;
}
if (appState.selectedBook != null) {
appState.selectedBook = null;
}
notifyListeners();
return true;
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
if (path is BooksListPath) {
appState.selectedIndex = 0;
appState.selectedBook = null;
} else if (path is BooksSettingsPath) {
appState.selectedIndex = 1;
} else if (path is BooksDetailsPath) {
appState.selectedIndex = 0;
appState.setSelectedBookById(path.id);
}
}
}
// Routes
abstract class BookRoutePath {}
class BooksListPath extends BookRoutePath {}
class BooksSettingsPath extends BookRoutePath {}
class BooksDetailsPath extends BookRoutePath {
final int id;
BooksDetailsPath(this.id);
}
// Widget that contains the AdaptiveNavigationScaffold
class AppShell extends StatefulWidget {
final BooksAppState appState;
AppShell({
@required this.appState,
});
@override
_AppShellState createState() => _AppShellState();
}
class _AppShellState extends State<AppShell> {
InnerRouterDelegate _routerDelegate;
ChildBackButtonDispatcher _backButtonDispatcher;
void initState() {
super.initState();
_routerDelegate = InnerRouterDelegate(widget.appState);
}
@override
void didUpdateWidget(covariant AppShell oldWidget) {
super.didUpdateWidget(oldWidget);
_routerDelegate.appState = widget.appState;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Defer back button dispatching to the child router
_backButtonDispatcher = Router.of(context)
.backButtonDispatcher
.createChildBackButtonDispatcher();
}
@override
Widget build(BuildContext context) {
var appState = widget.appState;
// Claim priority, If there are parallel sub router, you will need
// to pick which one should take priority;
_backButtonDispatcher.takePriority();
return Scaffold(
appBar: AppBar(),
body: Router(
routerDelegate: _routerDelegate,
backButtonDispatcher: _backButtonDispatcher,
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: 'Settings'),
],
currentIndex: appState.selectedIndex,
onTap: (newIndex) {
appState.selectedIndex = newIndex;
},
),
);
}
}
class InnerRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
BooksAppState get appState => _appState;
BooksAppState _appState;
set appState(BooksAppState value) {
if (value == _appState) {
return;
}
_appState = value;
notifyListeners();
}
InnerRouterDelegate(this._appState);
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
if (appState.selectedIndex == 0) ...[
FadeAnimationPage(
child: BooksListScreen(
books: appState.books,
onTapped: _handleBookTapped,
),
key: ValueKey('BooksListPage'),
),
if (appState.selectedBook != null)
MaterialPage(
key: ValueKey(appState.selectedBook),
child: BookDetailsScreen(book: appState.selectedBook),
),
] else
FadeAnimationPage(
child: SettingsScreen(),
key: ValueKey('SettingsPage'),
),
],
onPopPage: (route, result) {
appState.selectedBook = null;
notifyListeners();
return route.didPop(result);
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
// This is not required for inner router delegate because it does not
// parse route
assert(false);
}
void _handleBookTapped(Book book) {
appState.selectedBook = book;
notifyListeners();
}
}
class FadeAnimationPage extends Page {
final Widget child;
FadeAnimationPage({Key key, this.child}) : super(key: key);
Route createRoute(BuildContext context) {
return PageRouteBuilder(
settings: this,
pageBuilder: (context, animation, animation2) {
var curveTween = CurveTween(curve: Curves.easeIn);
return FadeTransition(
opacity: animation.drive(curveTween),
child: child,
);
},
);
}
}
// Screens
class BooksListScreen extends StatelessWidget {
final List<Book> books;
final ValueChanged<Book> onTapped;
BooksListScreen({
@required this.books,
@required this.onTapped,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
for (var book in books)
ListTile(
title: Text(book.title),
subtitle: Text(book.author),
onTap: () => onTapped(book),
)
],
),
);
}
}
class BookDetailsScreen extends StatelessWidget {
final Book book;
BookDetailsScreen({
@required this.book,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Back'),
),
if (book != null) ...[
Text(book.title, style: Theme.of(context).textTheme.headline6),
Text(book.author, style: Theme.of(context).textTheme.subtitle1),
],
],
),
),
);
}
}
class SettingsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Settings screen'),
),
);
}
}
如果您希望主页导航按钮 link 到主页并且不保持状态,则必须将 set selectedIndex 替换为:
set selectedIndex(int idx) {
_selectedIndex = idx;
if (_selectedIndex == 1) {
// Remove this line if you want to keep the selected book when navigating
// between "settings" and "home" which book was selected when Settings is
// tapped.
selectedBook = null;
}
notifyListeners();
}
您可能想看看在编写自己的 RouteInformationParser 时如何提取查询参数: Parsing a URI to extract query parameters, with Dart
这是您可能想要了解 Navigator 2.0 的另一个示例:https://github.com/flutter/flutter/pull/63424
来自此 gist 的工作底部导航与 flutter sdk >= 2.12
兼容import 'package:flutter/material.dart';
void main() {
runApp(NestedRouterDemo());
}
class Book {
final String title;
final String author;
Book(this.title, this.author);
}
class NestedRouterDemo extends StatefulWidget {
@override
_NestedRouterDemoState createState() => _NestedRouterDemoState();
}
class _NestedRouterDemoState extends State<NestedRouterDemo> {
BookRouterDelegate _routerDelegate = BookRouterDelegate();
BookRouteInformationParser _routeInformationParser = BookRouteInformationParser();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Books App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
class BooksAppState extends ChangeNotifier {
int _selectedIndex;
Book? _selectedBook;
final List<Book> books = [
Book('Stranger in a Strange Land', 'Robert A. Heinlein'),
Book('Foundation', 'Isaac Asimov'),
Book('Fahrenheit 451', 'Ray Bradbury'),
];
BooksAppState() : _selectedIndex = 0;
int get selectedIndex => _selectedIndex;
set selectedIndex(int idx) {
_selectedIndex = idx;
notifyListeners();
}
Book? get selectedBook => _selectedBook;
set selectedBook(Book? book) {
_selectedBook = book;
notifyListeners();
}
int? getSelectedBookById() {
if (_selectedBook == null || !books.contains(_selectedBook)) return null;
return books.indexOf(_selectedBook!);
}
void setSelectedBookById(int id) {
if (id < 0 || id > books.length - 1) {
return;
}
_selectedBook = books[id];
notifyListeners();
}
}
class BookRouteInformationParser extends RouteInformationParser<BookRoutePath> {
@override
Future<BookRoutePath> parseRouteInformation(RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location ?? '');
if (uri.pathSegments.isNotEmpty && uri.pathSegments.first == 'settings') {
return BooksSettingsPath();
} else {
if (uri.pathSegments.length >= 2) {
if (uri.pathSegments[0] == 'book') {
return BooksDetailsPath(int.tryParse(uri.pathSegments[1]));
}
}
return BooksListPath();
}
}
@override
RouteInformation restoreRouteInformation(BookRoutePath configuration) {
if (configuration is BooksListPath) {
return RouteInformation(location: '/home');
}
if (configuration is BooksSettingsPath) {
return RouteInformation(location: '/settings');
}
if (configuration is BooksDetailsPath) {
return RouteInformation(location: '/book/${configuration.id}');
}
return RouteInformation();
}
}
class BookRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
final GlobalKey<NavigatorState> navigatorKey;
BooksAppState appState = BooksAppState();
BookRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
appState.addListener(notifyListeners);
}
BookRoutePath get currentConfiguration {
if (appState.selectedIndex == 1) {
return BooksSettingsPath();
} else {
if (appState.selectedBook == null) {
return BooksListPath();
} else {
return BooksDetailsPath(appState.getSelectedBookById());
}
}
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage(
child: AppShell(appState: appState),
),
],
onPopPage: (route, result) {
if (!route.didPop(result)) {
return false;
}
if (appState.selectedBook != null) {
appState.selectedBook = null;
}
notifyListeners();
return true;
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
if (path is BooksListPath) {
appState.selectedIndex = 0;
appState.selectedBook = null;
} else if (path is BooksSettingsPath) {
appState.selectedIndex = 1;
} else if (path is BooksDetailsPath && path.id != null) {
appState.setSelectedBookById(path.id!);
}
}
}
// Routes
abstract class BookRoutePath {}
class BooksListPath extends BookRoutePath {}
class BooksSettingsPath extends BookRoutePath {}
class BooksDetailsPath extends BookRoutePath {
final int? id;
BooksDetailsPath(this.id);
}
// Widget that contains the AdaptiveNavigationScaffold
class AppShell extends StatefulWidget {
final BooksAppState appState;
AppShell({
required this.appState,
});
@override
_AppShellState createState() => _AppShellState();
}
class _AppShellState extends State<AppShell> {
late InnerRouterDelegate _routerDelegate;
late ChildBackButtonDispatcher _backButtonDispatcher;
void initState() {
super.initState();
_routerDelegate = InnerRouterDelegate(widget.appState);
}
@override
void didUpdateWidget(covariant AppShell oldWidget) {
super.didUpdateWidget(oldWidget);
_routerDelegate.appState = widget.appState;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Defer back button dispatching to the child router
_backButtonDispatcher = Router.of(context).backButtonDispatcher!.createChildBackButtonDispatcher();
}
@override
Widget build(BuildContext context) {
var appState = widget.appState;
// Claim priority, If there are parallel sub router, you will need
// to pick which one should take priority;
_backButtonDispatcher.takePriority();
return Scaffold(
appBar: AppBar(),
body: Router(
routerDelegate: _routerDelegate,
backButtonDispatcher: _backButtonDispatcher,
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.settings), label: 'Settings'),
],
currentIndex: appState.selectedIndex,
onTap: (newIndex) {
appState.selectedIndex = newIndex;
},
),
);
}
}
class InnerRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
BooksAppState get appState => _appState;
BooksAppState _appState;
set appState(BooksAppState value) {
if (value == _appState) {
return;
}
_appState = value;
notifyListeners();
}
InnerRouterDelegate(this._appState);
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
if (appState.selectedIndex == 0) ...[
FadeAnimationPage(
child: BooksListScreen(
books: appState.books,
onTapped: _handleBookTapped,
),
key: ValueKey('BooksListPage'),
),
if (appState.selectedBook != null)
MaterialPage(
key: ValueKey(appState.selectedBook),
child: BookDetailsScreen(book: appState.selectedBook!),
),
] else
FadeAnimationPage(
child: SettingsScreen(),
key: ValueKey('SettingsPage'),
),
],
onPopPage: (route, result) {
appState.selectedBook = null;
notifyListeners();
return route.didPop(result);
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
// This is not required for inner router delegate because it does not
// parse route
assert(false);
}
void _handleBookTapped(Book book) {
appState.selectedBook = book;
notifyListeners();
}
}
class FadeAnimationPage extends Page {
final Widget child;
FadeAnimationPage({required LocalKey key, required this.child}) : super(key: key);
Route createRoute(BuildContext context) {
return PageRouteBuilder(
settings: this,
pageBuilder: (context, animation, animation2) {
var curveTween = CurveTween(curve: Curves.easeIn);
return FadeTransition(
opacity: animation.drive(curveTween),
child: child,
);
},
);
}
}
// Screens
class BooksListScreen extends StatelessWidget {
final List<Book> books;
final ValueChanged<Book> onTapped;
BooksListScreen({
required this.books,
required this.onTapped,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
for (var book in books)
ListTile(
title: Text(book.title),
subtitle: Text(book.author),
onTap: () => onTapped(book),
)
],
),
);
}
}
class BookDetailsScreen extends StatelessWidget {
final Book book;
BookDetailsScreen({
required this.book,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Back'),
),
Text(book.title, style: Theme.of(context).textTheme.headline6),
Text(book.author, style: Theme.of(context).textTheme.subtitle1),
],
),
),
);
}
}
class SettingsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Settings screen'),
),
);
}
}
我一直在寻找这个问题的答案太久了。我在一个我正在从事的项目上进行了 2 周和 13 次迭代,但我仍然对我拥有的许多解决方案中的任何一个都不满意 seen/tried 因为他们中的每一个都有至少一个我已经结束的主要妥协努力学习。我想我现在已经花了足够多的时间在这上面,可以说 flutter 还没有针对这个用例进行裁剪(不是优雅或简单,也不会破坏其他 flutter 功能)。它们“支持”网络,但目前,它们并未针对网络进行优化,而且很难创建模仿网络行为的应用程序。然而,这并不奇怪,因为他们基本上在 Flutter 2022 Strategy:
中声明自己Flutter shipped the first stable release of web support in 2021, and it remains too early to predict its ultimate success. Yet the web developer market is huge (10m+) and Flutter offers something distinctive for this audience compared to traditional DOM-based frameworks. As new technologies like CanvasKit, WebGPU, AOM, and WebAssembly with GC become available, Flutter is in a unique position of being able to target web apps designed for this new web generation. Its layered approach is well suited for targeting Canvas and WebGPU; Dart compiles to highly-optimized JavaScript today and will support WebAssembly in the future; and our consistent, Flutter's approachable API is a notable contrast to the complex “batteries not included” web ecosystem. Even if our role in the immediate future is a niche one, the web ecosystem is large enough that their niche is our growth opportunity.
然而,flutters cross-platform 功能可不是闹着玩的,因此我什至不厌其烦地花费大量时间和精力来尝试找到解决方案,而这些事情本可以用不到 10 分钟的时间来完成使用我的网络背景。我相信很多其他人都是这种情况,所以这里是下面答案的更新和改进版本,它适用于最新版本的 flutter 和 null safety,并且还使用 built-in 后退按钮而不是自定义按钮实现其他答案使用:
import 'package:flutter/material.dart';
void main() {
runApp(const NestedRouterDemo());
}
class Book {
final String title;
final String author;
Book(this.title, this.author);
}
class NestedRouterDemo extends StatefulWidget {
const NestedRouterDemo({Key? key}) : super(key: key);
@override
_NestedRouterDemoState createState() => _NestedRouterDemoState();
}
class _NestedRouterDemoState extends State<NestedRouterDemo> {
final BookRouterDelegate _routerDelegate = BookRouterDelegate();
final BookRouteInformationParser _routeInformationParser =
BookRouteInformationParser();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Books App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
class BooksAppState extends ChangeNotifier {
int _selectedIndex;
Book? _selectedBook;
final List<Book> books = [
Book('Stranger in a Strange Land', 'Robert A. Heinlein'),
Book('Foundation', 'Isaac Asimov'),
Book('Fahrenheit 451', 'Ray Bradbury'),
];
BooksAppState() : _selectedIndex = 0;
int get selectedIndex => _selectedIndex;
set selectedIndex(int idx) {
_selectedIndex = idx;
// uncomment this line if you dont want to keep the selected book when navigating
// between "settings" and "home" although if your doing this you should only really need 1 nested navigator for the whole app
// if (_selectedIndex == 1) {
// selectedBook = null;
// }
notifyListeners();
}
Book? get selectedBook => _selectedBook;
set selectedBook(Book? book) {
_selectedBook = book;
notifyListeners();
}
int getSelectedBookById() {
if (!books.contains(_selectedBook)) return 0;
return books.indexOf(_selectedBook!);
}
void setSelectedBookById(int id) {
if (id < 0 || id > books.length - 1) {
return;
}
_selectedBook = books[id];
notifyListeners();
}
}
class BookRouteInformationParser extends RouteInformationParser<BookRoutePath> {
@override
Future<BookRoutePath> parseRouteInformation(
RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location!);
if (uri.pathSegments.isNotEmpty && uri.pathSegments.first == 'settings') {
return BooksSettingsPath();
} else {
if (uri.pathSegments.length >= 2) {
if (uri.pathSegments[0] == 'book') {
return BooksDetailsPath(int.tryParse(uri.pathSegments[1])!);
}
}
return BooksListPath();
}
}
@override
RouteInformation? restoreRouteInformation(BookRoutePath configuration) {
if (configuration is BooksListPath) {
return const RouteInformation(location: '/home');
}
if (configuration is BooksSettingsPath) {
return const RouteInformation(location: '/settings');
}
if (configuration is BooksDetailsPath) {
return RouteInformation(location: '/book/${configuration.id}');
}
return null;
}
}
class BookRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
@override
final GlobalKey<NavigatorState> navigatorKey;
BooksAppState appState = BooksAppState();
BookRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
appState.addListener(notifyListeners);
}
@override
BookRoutePath get currentConfiguration {
if (appState.selectedIndex == 1) {
return BooksSettingsPath();
} else {
if (appState.selectedBook == null) {
return BooksListPath();
} else {
return BooksDetailsPath(appState.getSelectedBookById());
}
}
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage(
child: AppShell(appState: appState),
),
],
onPopPage: (route, result) {
if (!route.didPop(result)) {
return false;
}
if (appState.selectedBook != null) {
appState.selectedBook = null;
}
notifyListeners();
return true;
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath configuration) async {
if (configuration is BooksListPath) {
appState.selectedIndex = 0;
appState.selectedBook = null;
} else if (configuration is BooksSettingsPath) {
appState.selectedIndex = 1;
} else if (configuration is BooksDetailsPath) {
appState.selectedIndex = 0;
appState.setSelectedBookById(configuration.id);
}
}
}
// Routes
abstract class BookRoutePath {}
class BooksListPath extends BookRoutePath {}
class BooksSettingsPath extends BookRoutePath {}
class BooksDetailsPath extends BookRoutePath {
final int id;
BooksDetailsPath(this.id);
}
// Widget that contains the AdaptiveNavigationScaffold
class AppShell extends StatefulWidget {
final BooksAppState appState;
const AppShell({
Key? key,
required this.appState,
}) : super(key: key);
@override
_AppShellState createState() => _AppShellState();
}
class _AppShellState extends State<AppShell> {
late InnerRouterDelegate _routerDelegate;
late ChildBackButtonDispatcher _backButtonDispatcher;
@override
void initState() {
super.initState();
_routerDelegate = InnerRouterDelegate(widget.appState);
}
@override
void didUpdateWidget(covariant AppShell oldWidget) {
super.didUpdateWidget(oldWidget);
_routerDelegate.appState = widget.appState;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Defer back button dispatching to the child router
_backButtonDispatcher = Router.of(context)
.backButtonDispatcher!
.createChildBackButtonDispatcher();
}
@override
Widget build(BuildContext context) {
var appState = widget.appState;
// Claim priority, If there are parallel sub router, you will need
// to pick which one should take priority;
_backButtonDispatcher.takePriority();
return Scaffold(
body: SizedBox(
height: double.infinity,
width: double.infinity,
child: Router(
routerDelegate: _routerDelegate,
backButtonDispatcher: _backButtonDispatcher,
),
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: 'Settings'),
],
currentIndex: appState.selectedIndex,
onTap: (newIndex) {
appState.selectedIndex = newIndex;
},
),
);
}
}
class InnerRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
@override
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
BooksAppState get appState => _appState;
BooksAppState _appState;
set appState(BooksAppState value) {
if (value == _appState) {
return;
}
_appState = value;
notifyListeners();
}
InnerRouterDelegate(this._appState);
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
if (appState.selectedIndex == 0) ...[
FadeAnimationPage(
child: BooksListScreen(
books: appState.books,
onTapped: _handleBookTapped,
),
key: const ValueKey('BooksListPage'),
),
if (appState.selectedBook != null)
MaterialPage(
key: ValueKey(appState.selectedBook),
child: BookDetailsScreen(book: appState.selectedBook!),
),
] else
const FadeAnimationPage(
child: SettingsScreen(),
key: ValueKey('SettingsPage'),
),
],
onPopPage: (route, result) {
appState.selectedBook = null;
notifyListeners();
return route.didPop(result);
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
// This is not required for inner router delegate because it does not
// parse route
assert(false);
}
void _handleBookTapped(Book book) {
appState.selectedBook = book;
notifyListeners();
}
}
class FadeAnimationPage extends Page {
final Widget child;
const FadeAnimationPage({required LocalKey key, required this.child})
: super(key: key);
@override
Route createRoute(BuildContext context) {
return PageRouteBuilder(
settings: this,
pageBuilder: (context, animation, animation2) {
var curveTween = CurveTween(curve: Curves.easeIn);
return FadeTransition(
opacity: animation.drive(curveTween),
child: child,
);
},
);
}
}
// Screens
class BooksListScreen extends StatelessWidget {
final List<Book> books;
final ValueChanged<Book> onTapped;
const BooksListScreen({
Key? key,
required this.books,
required this.onTapped,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Books'),
),
body: ListView(
children: [
for (var book in books)
ListTile(
title: Text(book.title),
subtitle: Text(book.author),
onTap: () => onTapped(book),
)
],
),
);
}
}
class BookDetailsScreen extends StatelessWidget {
final Book book;
const BookDetailsScreen({
Key? key,
required this.book,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(book.title),
),
body: Center(
child: SizedBox(
width: 200,
child: ListTile(
title: Text(book.title),
subtitle: Text(book.author),
),
),
),
);
}
}
class SettingsScreen extends StatelessWidget {
const SettingsScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Settings'),
),
body: const Center(
child: Text('Settings screen'),
),
);
}
}
还有一些额外的事情值得一提:
- 上面的这个例子似乎破坏了页面转换和英雄动画(因此使用 'FadeAnimationPage' 的原因)。我找到了这个 Flutter Navigator 2.0 for mobile dev: Nested navigators basics,它声称可以解决这个问题,但是我在这个例子中尝试实现它却没有成功
- 我只使用了这个例子,因为它是以前的答案并且被破坏了,但我认为这是矫枉过正的。我认为实现此类功能的最常见用例是尝试为仍然适用于路由的网络创建持久导航。为此,整个应用程序只需要一个嵌套导航器。我还读到嵌套导航器也会对性能产生重大影响,所以我实际上建议不要使用超过 1 个导航器,除非你有非常具体的原因。
- 最后,这个例子太复杂了,flutter 团队知道这一点。他们甚至开始 Flutter User Experience Research (UXR) to try and solve this however if I'm honest there is not as much activity on this as I would like to see. That is why I would recommend using a package such as GoRouter. They have a very well documented nested navigation tutorial here