flutter - 获取项目点击并传递给另一个类
问题描述
我有一个foods.dart 像这样
List<Map> foods = [
{
"img": "assets/food1.jpg",
"name": "burger"
},
{
"img": "assets/food2.jpg",
"name": "fries"
},
];
然后我有我的 CarouselSlider 像这样
CarouselSlider(
options: CarouselOptions(
height: MediaQuery.of(context).size.height/2.4,
autoPlay: true,//
viewportFraction: 1.0,
onPageChanged: (index, reason) {
setState(() {
_current = index;
});
}
),
items: map<Widget>(
foods,
(index, i){
Map food = foods[index];
return SliderItem(
img: food['img'],
name: food['name'],
);
},
).toList(),
),
还有我的slider.dart
class SliderItem extends StatelessWidget {
final String name;
final String img;
//final bool isFav;
//final double rating;
//final int raters;
SliderItem({
Key key,
@required this.name,
@required this.img})
//@required this.isFav,
//@required this.rating,
//@required this.raters})
:super(key: key);
@override
Widget build(BuildContext context) {
return InkWell(
child: ListView(
shrinkWrap: true,
primary: false,
children: <Widget>[
Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height / 3.2,
width: MediaQuery.of(context).size.width,
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.asset(
"$img",
fit: BoxFit.cover,
),
),
),
Positioned(
right: -10.0,
bottom: 3.0,
child: RawMaterialButton(
onPressed: (){},
elevation: 4.0,
child: Padding(
padding: EdgeInsets.all(5),
),
),
),
],
),
Padding(
padding: EdgeInsets.only(bottom: 2.0, top: 8.0),
child: Text(
"$name",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w900,
),
maxLines: 2,
),
),
],
),
onTap: (){
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context){
return ProductDetails();
},
),
);
},
);
}
}
我的问题是如何获取选择了哪个图像并将其传递到 ProductDetails 页面?
最好通过图像名称索引吗?
我不确定哪个是最好的方法
我希望我已经足够清楚了。我正在使用 carousel_slider: ^2.1.0 谢谢
解决方案
您可以将对象传递给导航中的另一个小部件,如下所示:
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return ProductDetails(
name: name,
img: img,
);
},
),
);
},
然后在ProductDetails小部件中,您可以获得如下参数:
class ProductDetails extends StatelessWidget {
final String name;
final String img;
const ProductDetails({Key key, @required this.name, @required this.img})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Text(
"$name",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w900,
),
maxLines: 2,
),
Image.asset(
"$img",
fit: BoxFit.cover,
),
],
),
);
}
}
但最好的解决方案是创建一个像Food这样的类,然后使用ListView.builder作为食物列表,然后为每个食物项目创建一个小部件,例如带有回调的SliderItem ,并在列表中的回调中导航到带有食物对象的ProductDetails 。
但问题是CarouselSlider采用小部件列表之类的项目,您不能使用ListView.builder,因此您在大食物列表中表现不佳。 https://youtu.be/vVg9It7cOfY