總結(jié)一下flutter內(nèi)部頁(yè)面關(guān)于導(dǎo)航的幾種用法:
一. 使用Navigator的push方法蝗砾,并實(shí)現(xiàn)MaterialPageRoute的build方法快鱼,打開(kāi)新頁(yè)面:
Navigator.push(context, MaterialPageRoute(builder: (_) {
return DetailScreen()
}
返回用navigator的pop方法
Navigator.pop(context);
二.用頁(yè)面的名字導(dǎo)航到不同頁(yè)面:
void main() {
runApp(MaterialApp(
title: 'navi base',
//1.設(shè)置初始頁(yè)面的名字.
initialRoute: '/',
//2.在runApp里初始化路由數(shù)組routes
routes: {
'/': (context) => FirstRoute(),
'/second': (context) => SecondRoute()
},
));
}
使用navigator的pushNamed方法push到對(duì)應(yīng)的頁(yè)面
Navigator.pushNamed(context, '/second');
三.導(dǎo)航時(shí)帶參數(shù):
1.用navigator的pushNamed方法push頁(yè)面,在arguments里加入?yún)?shù):
Navigator.pushNamed(context, ExtractArgumentsScreen.routeName,
arguments: ScreenArguments( 'Extract Arguments Screen', 'This message is extracted in the build method.', ),
);
在導(dǎo)航的目的頁(yè)面的build方法里用ModalRoute.of(context)方法獲取需要的參數(shù):
final ScreenArguments args = ModalRoute.of(context).settings.arguments;
2.或者使用onGenerateRoute方法:
MaterialApp(
onGenerateRoute: (settings) {
// 從這里拿到數(shù)據(jù)并解析
if (settings.name == PassArgumentsScreen.routeName) {
final ScreenArguments args = settings.arguments;
//解析成功之后再創(chuàng)建目的頁(yè)面幢码,傳遞參數(shù)
return MaterialPageRoute(
builder: (context) {
return PassArgumentsScreen(
title: args.title,
message: args.message,
);
},
);
}
},
);
四.返回的時(shí)候帶參數(shù):
第二個(gè)頁(yè)面返回到第一個(gè)頁(yè)面的時(shí)候如果要帶參數(shù)担平,可以使用async異步方法來(lái)實(shí)現(xiàn)
//......略.......
onPressed: () {
//button的點(diǎn)擊事件是一個(gè)異步方法:
_navigateAndDisplaySelection(context);
},
//......略.......
//實(shí)現(xiàn)這個(gè)異步方法
_navigateAndDisplaySelection(BuildContext context) async {
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
}
//獲取到返回值result之后進(jìn)行相應(yīng)的操作:
Scaffold.of(context)
..removeCurrentSnackBar()
..showSnackBar(SnackBar(content: Text("$result")));
.............
五.用頁(yè)面的初始化方法傳遞參數(shù):
class DetailScreen extends StatelessWidget {
//屬性
final Todo todo;
//聲明初始化方法的時(shí)候加上參數(shù)this.todo
DetailScreen({Key key, @required this.todo}) : super(key: key);
@override
Widget build(BuildContext context) {
// 生成UI
return Scaffold(
appBar: AppBar(
title: Text(todo.title),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Text(todo.description),
),
);
}
}
用navigator的push方法,在頁(yè)面的初始化方法中傳遞參數(shù):
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(todo: todos[index]),//用頁(yè)面的初始化方法傳遞參數(shù)
),
);
},