在Flutter中跨页移动数据



我希望能够将数据从一个屏幕传输到另一个屏幕。我现在拥有的确实有效,但我希望能够在AppBar,它只会转到第二页,不接受任何参数。现在我有这个:

第一页

这是第一页上的图标,它将列表平铺参数添加到Cart屏幕(只是添加了一个图标,它没有推送Cart屏幕应该在下面的appbar中完成。

child: IconButton(
icon: Icon(Icons.add),

onPressed: () => MaterialPageRoute(

builder: (context) =>
Cart(person.name, person.surname),
)),

在下面的脚手架中,我在AppBar中有这个图标,它应该只推送Cart屏幕,而不是任何其他值。

IconButton(
icon: Icon(Icons.add_shopping_cart, color: Colors.white),
//this will be the cart window ontap, change icon to something better
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
Cart(//there should be arguments here, but I just want to go to Cart screen, the arguments were added in the first icon))),

这个Cart类需要参数(来自第二页,比如personName、personSurname(,但我只想能够推送第二个屏幕,上面没有任何参数。它是应用程序栏中的小推车图标。

第二页

这是第二个页面(sudo cart屏幕(,应该只接受第一个页面中的参数。

class Cart extends StatefulWidget {

final String personName;
final String personSurname;
Cart(this.personName, this.personSurname);
@override
_CartState createState() => _CartState();
}
class _CartState extends State<Cart> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Cart'),
centerTitle: true,
),
body: Center(
child: Container(
child: Text('${widget.personName}, ${widget.personSurname}'))),
);
}
}

我的问题是,我想有两个单独的功能车。第一个在第一个图标所在的第一页只在购物车中添加我想要的任何参数,第一页应用程序栏中的第二个图标只会推送购物车屏幕。

在第二个屏幕中,我只想从第一页推送任何数据。

这样试试:

  1. 声明上面的两个变量:
String name = '';
String surname = '';
  1. 将数据分配给它们:
child: IconButton(
icon: Icon(Icons.add),
onPressed: () {
name = person.name;
surname = person.surname;
},
  1. 并将它们用作参数:
IconButton(
icon: Icon(Icons.add_shopping_cart, color: Colors.white),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>  Cart(name, surname))
),

最新更新