Flutter如何通过InkWell的onTap事件将ColorDott类的值传递给Colords类
解决方案
你需要通过回调函数实现子组件向父组件传值,具体修改步骤如下:
步骤1:修改ColorDott类,添加回调参数
给ColorDott添加点击回调属性,用于触发后向父组件传值:
class ColorDott extends StatefulWidget{ // 新增3个属性,存储当前Dot的颜色、索引和回调方法 final Color color; final int count; final Function(Color selectedColor, int selectedIndex) onSelected; // 修改构造方法 const ColorDott({ Key? key, required this.color, required this.count, required this.onSelected, }) : super(key: key); @override Colre createState() => Colre(); } class Colre extends State<ColorDott> { @override Widget build(BuildContext context) { return InkWell( onTap: () { // 点击时触发回调,把当前Dot的颜色和索引传递给父组件 widget.onSelected(widget.color, widget.count); }, // 你原来的Dot样式代码保留,这里给个参考实现 child: Container( margin: const EdgeInsets.only(right: 8), padding: const EdgeInsets.all(4), height: 40, width: 40, decoration: BoxDecoration( color: Colors.transparent, border: Border.all(color: widget.color), shape: BoxShape.circle, ), child: DecoratedBox( decoration: BoxDecoration( color: widget.color, shape: BoxShape.circle, ), ), ), ); } }
步骤2:修改Colords类,接收子组件传值
在Colords的State中定义变量存储选中值,绑定回调接收子组件传递的数据:
class Colords extends StatefulWidget{ final Product product; const Colords({Key? key, required this.product}) : super(key: key); @override Colr createState() => Colr(); } class Colr extends State<Colords> { final FirebaseAuth firebaseAuth = FirebaseAuth.instance; int numOfItems = 1; // 新增变量存储选中的颜色和对应索引 Color? selectedColor; int? selectedColorIndex; @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(20)), child: Column( children: [ Row( children: [ ...List.generate( widget.product.colors.length, (index) => ColorDott( color: widget.product.colors[index], count: index, // 绑定回调,接收子组件传过来的值 onSelected: (color, index) { setState(() { selectedColor = color; selectedColorIndex = index; }); // 测试打印,确认传值成功 debugPrint("选中颜色:$selectedColor,选中索引:$selectedColorIndex"); }, ), ), // 你原来的数量增减按钮代码保留不变 const Spacer(), RoundedIconBtn( icon: Icons.remove, press: () { if (numOfItems > 1) { setState(() { numOfItems--; }); } }, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0 / 2), child: Text( numOfItems.toString().padLeft(2, "0"), style: Theme.of(context).textTheme.headline6, ), ), RoundedIconBtn( icon: Icons.add, showShadow: true, press: () { setState(() { numOfItems++; }); }, ), ], ), Row( children: [ Expanded( child: TopRoundedContainer( color: Colors.white, child: Padding( padding: EdgeInsets.only( left: SizeConfig.screenWidth * 0.15, right: SizeConfig.screenWidth * 0.15, bottom: getProportionateScreenWidth(40), top: getProportionateScreenWidth(15), ), child: DefaultButton( text: "Add To Cart", press: () { // 加入购物车时可以直接使用selectedColor变量 debugPrint("提交时选中颜色:$selectedColor"); }, ), ), ), ) ], ), ] ), ); } }
修改完成后点击ColorDott就可以实时把选中的颜色值传递到Colords类中,不会再出现null的问题。
内容的提问来源于stack exchange,提问作者Emad Aljumaily
相关产品推荐
相关产品推荐

