當使用 Navigator.push()
跳轉到其他頁面時,可順便傳遞資料。
Version
Flutter 3.24.5
Flutter
- Android 與 iOS 都成功使用
Navigator.push()
實現跳轉頁面並傳遞資料
Navigator
part_a.dart
import 'package:flutter/material.dart';
import 'package:flutter_lab/page_b.dart';
class PageA extends StatefulWidget {
const PageA({super.key});
State<PageA> createState() => _PageA();
}
class _PageA extends State<PageA> {
final _name = 'Sam';
final _id = 123;
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text(
'Page A',
),
);
var floatingActionButton = FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PageB(
name: _name,
id: _id,
),
),
);
},
child: const Icon(
Icons.navigate_next,
),
);
var body = Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Name: $_name",
),
Text(
"ID: $_id",
),
],
),
);
return Scaffold(
appBar: appBar,
floatingActionButton: floatingActionButton,
body: body,
);
}
}
Line 24
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PageB(
name: _name,
id: _id,
),
),
);
}
Navigator.push()
:一樣使用Navigator.push()
跳轉頁面,但在 View 傳入資料name
:可在 PageB 自行定義參數名稱
part_b.dart
import 'package:flutter/material.dart';
class PageB extends StatefulWidget {
final String name;
final int id;
const PageB({
super.key,
required this.name,
required this.id,
});
State<PageB> createState() => _PageB();
}
class _PageB extends State<PageB> {
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text(
'Page B',
),
);
var body = Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Name: ${widget.name}",
),
Text(
"ID: ${widget.id}",
),
],
),
);
return Scaffold(
appBar: appBar,
body: body,
);
}
}
Line 3
class PageB extends StatefulWidget {
final String name;
final int id;
const PageB({
super.key,
required this.name,
required this.id,
});
State<PageB> createState() => _PageB();
}
final String name
:以final
定義參數名稱
與型別
PageB()
:在 PageB 的 constructor 以required this
加上參數名稱
,會自動將傳遞資料
寫入變數
- 資料名稱
不能
如 state 一樣以底線
命名
Line 26
var body = Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Name: ${widget.name}",
),
Text(
"ID: ${widget.id}",
),
],
),
)
widget.name
:由於傳遞資料不是
state,必須以widget
的形式取得
Conclusion
- 所傳的資料不是 state,因此
命名方式
與取得方式
與 state 不同