一、push 方法向第二个页面传值
flutter navigator push页面传递参数有两个方法:
1、navigator push MaterialPageRoute 直接传递
Navigator.push(context,MaterialPageRoute(builder: (context) => DetailScreen(todo: todos[index]),),);
2、使用 RouteSettings 传递参数
class DetailScreen extends StatelessWidget {@overrideWidget build(BuildContext context) {final Todo todo = ModalRoute.of(context).settings.arguments;// Use the Todo to create the UI.return Scaffold(appBar: AppBar(title: Text(todo.title),),body: Padding(padding: EdgeInsets.all(16.0),child: Text(todo.description),),);}
}
Navigator.push(context,MaterialPageRoute(builder: (context) => DetailScreen(),// Pass the arguments as part of the RouteSettings. The// DetailScreen reads the arguments from these settings.settings: RouteSettings(arguments: todos[index],),),);
二、pop回来传值
传值
//Yep 按钮
ElevatedButton(onPressed: () {// The Yep button returns "Yep!" as the result.Navigator.pop(context, 'Yep!');},child: Text('Yep!'),
);//Nope 按钮
ElevatedButton(onPressed: () {// The Nope button returns "Nope!" as the result.Navigator.pop(context, 'Nope!');},child: Text('Nope!'),
);
接收传值
_navigateAndDisplaySelection(BuildContext context) async {final result = await Navigator.push(context,MaterialPageRoute(builder: (context) => SelectionScreen()),);// After the Selection Screen returns a result, hide any previous snackbars// and show the new result.// 等选择界面返回结果,先隐藏之前的 snackbars,结果显示在新的 snackbars 里 (After the Selection Screen returns a result, hide any previous snackbars and show the new result!)Scaffold.of(context)..removeCurrentSnackBar()..showSnackBar(SnackBar(content: Text("$result")));
}