建立巢狀導航流
應用程式隨著時間的推移會累積數十個甚至數百個路由。您的一些路由可以作為頂級(全域性)路由。例如,"/", "profile", "contact", "social_feed" 都可以是您應用內的頂級路由。但是,想象一下您在頂級的 Navigator widget 中定義了所有可能的路由。列表會非常長,而且許多這些路由最好巢狀在另一個 widget 中進行處理。
考慮一個用於您透過應用程式控制的無線燈泡的物聯網 (IoT) 設定流程。此設定流程包含四個頁面
find_devices頁面:查詢附近的燈泡。select_device頁面:選擇要新增的燈泡。connecting頁面:新增燈泡。finished頁面:完成設定。
您可以從頂級的 Navigator widget orchestrate 此行為。但是,在 SetupFlow widget 中定義第二個巢狀的 Navigator widget 會更有意義,並讓巢狀的 Navigator 負責設定流程中的四個頁面。這種導航委託能夠實現更強的本地控制,這在開發軟體時通常是首選。
以下動畫展示了應用程式的行為

在本食譜中,您將實現一個四頁的物聯網設定流程,該流程將維護自己的導航,巢狀在頂級 Navigator widget 下方。
準備導航
#此物聯網應用程式有兩個頂級螢幕以及設定流程。將這些路由名稱定義為常量,以便可以在程式碼中引用它們。
const routeHome = '/';
const routeSettings = '/settings';
const routePrefixDeviceSetup = '/setup/';
const routeDeviceSetupStart = '/setup/$routeDeviceSetupStartPage';
const routeDeviceSetupStartPage = 'find_devices';
const routeDeviceSetupSelectDevicePage = 'select_device';
const routeDeviceSetupConnectingPage = 'connecting';
const routeDeviceSetupFinishedPage = 'finished';主螢幕和設定螢幕使用靜態名稱引用。但是,設定流程頁面使用兩個路徑來建立它們的路由名稱:一個 /setup/ 字首後跟特定頁面的名稱。透過組合這兩個路徑,您的 Navigator 可以確定路由名稱是用於設定流程的,而無需識別與設定流程關聯的所有單個頁面。
頂級 Navigator 不負責識別單獨的設定流程頁面。因此,您的頂級 Navigator 需要解析傳入的路由名稱以識別設定流程字首。需要解析路由名稱意味著您不能使用頂級 Navigator 的 routes 屬性。相反,您必須為 onGenerateRoute 屬性提供一個函式。
實現 onGenerateRoute 以為三個頂級路徑中的每一個返回適當的 widget。
onGenerateRoute: (settings) {
final Widget page;
if (settings.name == routeHome) {
page = const HomeScreen();
} else if (settings.name == routeSettings) {
page = const SettingsScreen();
} else if (settings.name!.startsWith(routePrefixDeviceSetup)) {
final subRoute = settings.name!.substring(
routePrefixDeviceSetup.length,
);
page = SetupFlow(setupPageRoute: subRoute);
} else {
throw Exception('Unknown route: ${settings.name}');
}
return MaterialPageRoute<void>(
builder: (context) {
return page;
},
settings: settings,
);
},請注意,主螢幕和設定螢幕路由與精確的路由名稱匹配。但是,設定流程路由條件僅檢查字首。如果路由名稱包含設定流程字首,則其餘路由名稱將被忽略並傳遞給 SetupFlow widget 進行處理。這種路由名稱的分離允許頂級 Navigator 對設定流程中的各種子路由保持不可知。
建立一個名為 SetupFlow 的有狀態 widget,它接受一個路由名稱。
class SetupFlow extends StatefulWidget {
const SetupFlow({super.key, required this.setupPageRoute});
final String setupPageRoute;
@override
State<SetupFlow> createState() => SetupFlowState();
}
class SetupFlowState extends State<SetupFlow> {
//...
}為設定流程顯示應用欄
#設定流程顯示一個持久的應用欄,該應用欄會出現在所有頁面上。
從 SetupFlow widget 的 build() 方法返回一個 Scaffold widget,幷包含所需的 AppBar widget。
@override
Widget build(BuildContext context) {
return Scaffold(appBar: _buildFlowAppBar(), body: const SizedBox());
}
PreferredSizeWidget _buildFlowAppBar() {
return AppBar(title: const Text('Bulb Setup'));
}應用欄顯示一個返回箭頭,並在按下返回箭頭時退出設定流程。但是,退出流程會導致使用者丟失所有進度。因此,使用者會被提示確認他們是否要退出設定流程。
提示使用者確認退出設定流程,並確保在使用者按下裝置上的硬體返回按鈕時顯示提示。
Future<void> _onExitPressed() async {
final isConfirmed = await _isExitDesired();
if (isConfirmed && mounted) {
_exitSetup();
}
}
Future<bool> _isExitDesired() async {
return await showDialog<bool>(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Are you sure?'),
content: const Text(
'If you exit device setup, your progress will be lost.',
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: const Text('Leave'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: const Text('Stay'),
),
],
);
},
) ??
false;
}
void _exitSetup() {
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) async {
if (didPop) return;
if (await _isExitDesired() && context.mounted) {
_exitSetup();
}
},
child: Scaffold(appBar: _buildFlowAppBar(), body: const SizedBox()),
);
}
PreferredSizeWidget _buildFlowAppBar() {
return AppBar(
leading: IconButton(
onPressed: _onExitPressed,
icon: const Icon(Icons.chevron_left),
),
title: const Text('Bulb Setup'),
);
}當用戶點選應用欄中的返回箭頭,或按下裝置上的返回按鈕時,會彈出一個警報對話方塊,以確認使用者是否要離開設定流程。如果使用者按下 **Leave**,則設定流程會從頂級導航堆疊中彈出自身。如果使用者按下 **Stay**,則操作將被忽略。
您可能會注意到 Navigator.pop() 同時被 **Leave** 和 **Stay** 按鈕呼叫。需要明確的是,此 pop() 操作會從導航堆疊中彈出警報對話方塊,而不是設定流程。
生成巢狀路由
#設定流程的職責是顯示流程中相應的頁面。
向 SetupFlow 新增一個 Navigator widget,並實現 onGenerateRoute 屬性。
final _navigatorKey = GlobalKey<NavigatorState>();
void _onDiscoveryComplete() {
_navigatorKey.currentState!.pushNamed(routeDeviceSetupSelectDevicePage);
}
void _onDeviceSelected(String deviceId) {
_navigatorKey.currentState!.pushNamed(routeDeviceSetupConnectingPage);
}
void _onConnectionEstablished() {
_navigatorKey.currentState!.pushNamed(routeDeviceSetupFinishedPage);
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) async {
if (didPop) return;
if (await _isExitDesired() && context.mounted) {
_exitSetup();
}
},
child: Scaffold(
appBar: _buildFlowAppBar(),
body: Navigator(
key: _navigatorKey,
initialRoute: widget.setupPageRoute,
onGenerateRoute: _onGenerateRoute,
),
),
);
}
Route<Widget> _onGenerateRoute(RouteSettings settings) {
final page = switch (settings.name) {
routeDeviceSetupStartPage => WaitingPage(
message: 'Searching for nearby bulb...',
onWaitComplete: _onDiscoveryComplete,
),
routeDeviceSetupSelectDevicePage => SelectDevicePage(
onDeviceSelected: _onDeviceSelected,
),
routeDeviceSetupConnectingPage => WaitingPage(
message: 'Connecting...',
onWaitComplete: _onConnectionEstablished,
),
routeDeviceSetupFinishedPage => FinishedPage(onFinishPressed: _exitSetup),
_ => throw StateError('Unexpected route name: ${settings.name}!'),
};
return MaterialPageRoute(
builder: (context) {
return page;
},
settings: settings,
);
}_onGenerateRoute 函式的工作方式與頂級 Navigator 相同。將一個 RouteSettings 物件傳遞給函式,其中包含路由的 name。基於該路由名稱,將返回四個流程頁面中的一個。
第一個頁面稱為 find_devices,它會等待幾秒鐘以模擬網路掃描。等待期過後,該頁面會呼叫其回撥。在這種情況下,回撥是 _onDiscoveryComplete。設定流程會識別出,在裝置發現完成時,應該顯示裝置選擇頁面。因此,在 _onDiscoveryComplete 中,_navigatorKey 指示巢狀的 Navigator 導航到 select_device 頁面。
select_device 頁面要求使用者從可用裝置列表中選擇一個裝置。在本食譜中,只向用戶呈現一個裝置。當用戶點選裝置時,會呼叫 onDeviceSelected 回撥。設定流程會識別出,當裝置被選中時,應該顯示連線頁面。因此,在 _onDeviceSelected 中,_navigatorKey 指示巢狀的 Navigator 導航到 "connecting" 頁面。
connecting 頁面與 find_devices 頁面的工作方式相同。connecting 頁面等待幾秒鐘,然後呼叫其回撥。在這種情況下,回撥是 _onConnectionEstablished。設定流程會識別出,在建立連線後,應該顯示最後一個頁面。因此,在 _onConnectionEstablished 中,_navigatorKey 指示巢狀的 Navigator 導航到 finished 頁面。
finished 頁面為使用者提供一個 **Finish** 按鈕。當用戶點選 **Finish** 時,會呼叫 _exitSetup 回撥,該回調會將整個設定流程從頂級 Navigator 堆疊中彈出,將使用者帶回到主螢幕。
恭喜!您已實現了帶有四個子路由的巢狀導航。
互動示例
#執行應用
- 在 **新增您的第一個燈泡** 螢幕上,點選 FAB(帶有加號 **+** 的圖示)。這將帶您進入 **選擇附近裝置** 螢幕。列出了一個燈泡。
- 點選列出的燈泡。會出現 **完成!** 螢幕。
- 點選 **完成** 按鈕返回到第一個螢幕。
import 'package:flutter/material.dart';
const routeHome = '/';
const routeSettings = '/settings';
const routePrefixDeviceSetup = '/setup/';
const routeDeviceSetupStart = '/setup/$routeDeviceSetupStartPage';
const routeDeviceSetupStartPage = 'find_devices';
const routeDeviceSetupSelectDevicePage = 'select_device';
const routeDeviceSetupConnectingPage = 'connecting';
const routeDeviceSetupFinishedPage = 'finished';
void main() {
runApp(
MaterialApp(
theme: ThemeData(
brightness: Brightness.dark,
appBarTheme: const AppBarTheme(backgroundColor: Colors.blue),
floatingActionButtonTheme: const FloatingActionButtonThemeData(
backgroundColor: Colors.blue,
),
),
onGenerateRoute: (settings) {
final Widget page;
if (settings.name == routeHome) {
page = const HomeScreen();
} else if (settings.name == routeSettings) {
page = const SettingsScreen();
} else if (settings.name!.startsWith(routePrefixDeviceSetup)) {
final subRoute = settings.name!.substring(
routePrefixDeviceSetup.length,
);
page = SetupFlow(setupPageRoute: subRoute);
} else {
throw Exception('Unknown route: ${settings.name}');
}
return MaterialPageRoute<void>(
builder: (context) {
return page;
},
settings: settings,
);
},
debugShowCheckedModeBanner: false,
),
);
}
@immutable
class SetupFlow extends StatefulWidget {
static SetupFlowState of(BuildContext context) {
return context.findAncestorStateOfType<SetupFlowState>()!;
}
const SetupFlow({super.key, required this.setupPageRoute});
final String setupPageRoute;
@override
SetupFlowState createState() => SetupFlowState();
}
class SetupFlowState extends State<SetupFlow> {
final _navigatorKey = GlobalKey<NavigatorState>();
@override
void initState() {
super.initState();
}
void _onDiscoveryComplete() {
_navigatorKey.currentState!.pushNamed(routeDeviceSetupSelectDevicePage);
}
void _onDeviceSelected(String deviceId) {
_navigatorKey.currentState!.pushNamed(routeDeviceSetupConnectingPage);
}
void _onConnectionEstablished() {
_navigatorKey.currentState!.pushNamed(routeDeviceSetupFinishedPage);
}
Future<void> _onExitPressed() async {
final isConfirmed = await _isExitDesired();
if (isConfirmed && mounted) {
_exitSetup();
}
}
Future<bool> _isExitDesired() async {
return await showDialog<bool>(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Are you sure?'),
content: const Text(
'If you exit device setup, your progress will be lost.',
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: const Text('Leave'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: const Text('Stay'),
),
],
);
},
) ??
false;
}
void _exitSetup() {
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) async {
if (didPop) return;
if (await _isExitDesired() && context.mounted) {
_exitSetup();
}
},
child: Scaffold(
appBar: _buildFlowAppBar(),
body: Navigator(
key: _navigatorKey,
initialRoute: widget.setupPageRoute,
onGenerateRoute: _onGenerateRoute,
),
),
);
}
Route<Widget> _onGenerateRoute(RouteSettings settings) {
final page = switch (settings.name) {
routeDeviceSetupStartPage => WaitingPage(
message: 'Searching for nearby bulb...',
onWaitComplete: _onDiscoveryComplete,
),
routeDeviceSetupSelectDevicePage => SelectDevicePage(
onDeviceSelected: _onDeviceSelected,
),
routeDeviceSetupConnectingPage => WaitingPage(
message: 'Connecting...',
onWaitComplete: _onConnectionEstablished,
),
routeDeviceSetupFinishedPage => FinishedPage(onFinishPressed: _exitSetup),
_ => throw StateError('Unexpected route name: ${settings.name}!'),
};
return MaterialPageRoute(
builder: (context) {
return page;
},
settings: settings,
);
}
PreferredSizeWidget _buildFlowAppBar() {
return AppBar(
leading: IconButton(
onPressed: _onExitPressed,
icon: const Icon(Icons.chevron_left),
),
title: const Text('Bulb Setup'),
);
}
}
class SelectDevicePage extends StatelessWidget {
const SelectDevicePage({super.key, required this.onDeviceSelected});
final void Function(String deviceId) onDeviceSelected;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Select a nearby device:',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
height: 54,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: WidgetStateColor.resolveWith((states) {
return const Color(0xFF222222);
}),
),
onPressed: () {
onDeviceSelected('22n483nk5834');
},
child: const Text(
'Bulb 22n483nk5834',
style: TextStyle(fontSize: 24),
),
),
),
],
),
),
),
);
}
}
class WaitingPage extends StatefulWidget {
const WaitingPage({
super.key,
required this.message,
required this.onWaitComplete,
});
final String message;
final VoidCallback onWaitComplete;
@override
State<WaitingPage> createState() => _WaitingPageState();
}
class _WaitingPageState extends State<WaitingPage> {
@override
void initState() {
super.initState();
_startWaiting();
}
Future<void> _startWaiting() async {
await Future<dynamic>.delayed(const Duration(seconds: 3));
if (mounted) {
widget.onWaitComplete();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 32),
Text(widget.message),
],
),
),
),
);
}
}
class FinishedPage extends StatelessWidget {
const FinishedPage({super.key, required this.onFinishPressed});
final VoidCallback onFinishPressed;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 200,
height: 200,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Color(0xFF222222),
),
child: const Center(
child: Icon(
Icons.lightbulb,
size: 140,
color: Colors.white,
),
),
),
const SizedBox(height: 32),
const Text(
'Bulb added!',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
const SizedBox(height: 32),
ElevatedButton(
style: ButtonStyle(
padding: WidgetStateProperty.resolveWith((states) {
return const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
);
}),
backgroundColor: WidgetStateColor.resolveWith((states) {
return const Color(0xFF222222);
}),
shape: WidgetStateProperty.resolveWith((states) {
return const StadiumBorder();
}),
),
onPressed: onFinishPressed,
child: const Text('Finish', style: TextStyle(fontSize: 24)),
),
],
),
),
),
),
);
}
}
@immutable
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildAppBar(context),
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 200,
height: 200,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Color(0xFF222222),
),
child: Center(
child: Icon(
Icons.lightbulb,
size: 140,
color: Theme.of(context).scaffoldBackgroundColor,
),
),
),
const SizedBox(height: 32),
const Text(
'Add your first bulb',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).pushNamed(routeDeviceSetupStart);
},
child: const Icon(Icons.add),
),
);
}
PreferredSizeWidget _buildAppBar(BuildContext context) {
return AppBar(
title: const Text('Welcome'),
actions: [
IconButton(
icon: const Icon(Icons.settings),
onPressed: () {
Navigator.pushNamed(context, routeSettings);
},
),
],
);
}
}
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildAppBar(),
body: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: List.generate(8, (index) {
return Container(
width: double.infinity,
height: 54,
margin: const EdgeInsets.only(left: 16, right: 16, top: 16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: const Color(0xFF222222),
),
);
}),
),
),
);
}
PreferredSizeWidget _buildAppBar() {
return AppBar(title: const Text('Settings'));
}
}