前言
在 Flutter 中,當你從一個頁面導航到另一個頁面時,你可以傳遞資料給目標頁面。這可以通過 Navigator 和 ModalRoute 來實現。本文將介紹如何在頁面導航時傳遞資料,並展示具體的使用情境和程式碼範例。
使用情境
假設你有一個應用程序,它會接收推送通知。當用戶點擊通知時,你希望導航到一個特定的頁面並顯示通知的內容。
步驟
- 設置導航路由:在
MaterialApp 中設置導航路由。
- 導航並傳遞資料:使用
Navigator.pushNamed 方法導航到目標頁面並傳遞資料。
- 接收資料:在目標頁面中使用
ModalRoute 來接收傳遞過來的資料。
程式碼範例
1. 設置導航路由
在 main.dart 中設置導航路由:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import 'package:flutter/material.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
void main() { runApp(MyApp()); }
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: HomePage(), routes: { '/notification_screen': (context) => const NotificationPage(), }, ); } }
class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Home Page"), ), body: Center( child: Text("Welcome to Home Page"), ), ); } }
|
2. 導航並傳遞資料
假設你在某個地方接收到推送通知,並希望導航到 NotificationPage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| final navigatorKey = GlobalKey<NavigatorState>();
void handleMessage(RemoteMessage? message) { if (message == null) return;
navigatorKey.currentState?.pushNamed( '/notification_screen', arguments: message, ); }
Future initPushNotifications() async { FirebaseMessaging.instance.getInitialMessage().then(handleMessage); FirebaseMessaging.onMessageOpenedApp.listen(handleMessage); }
|
3. 接收資料
在 NotificationPage 中使用 ModalRoute 來接收傳遞過來的資料:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class NotificationPage extends StatelessWidget { const NotificationPage({super.key});
@override Widget build(BuildContext context) { final message = ModalRoute.of(context)?.settings.arguments as RemoteMessage?;
return Scaffold( appBar: AppBar( title: Text("Notification Page"), ), body: Center( child: message != null ? Text("Message: ${message.notification?.title ?? 'No Title'}") : Text("No message received"), ), ); } }
|
總結
- 設置導航路由:在
MaterialApp 中設置導航路由,定義頁面路徑和對應的頁面小部件。
- 導航並傳遞資料:使用
Navigator.pushNamed 方法導航到目標頁面,並通過 arguments 傳遞資料。
- 接收資料:在目標頁面中使用
ModalRoute.of(context)?.settings.arguments 來接收傳遞過來的資料。
這樣,你就可以在頁面導航時傳遞資料,並在目標頁面中使用這些資料。