Flutter自定义Bottom Sheet中RadioGroup无法获取选中值求助
解决Flutter自定义BottomSheet返回选中值的问题
原代码的核心问题是showModalBottomSheet是异步操作,但你用同步方式返回选中值,导致函数执行时用户还没选择就返回了空字符串;同时Radio按钮的状态管理也有问题,直接修改传入的initialValue不会正确更新UI。以下是修复方案:
关键改动说明
- 将
basicBottomSheet改为返回Future<String>,利用showModalBottomSheet的异步特性传递选中结果 - 在BottomSheet内部维护选中状态,确保Radio按钮的选中状态正确更新
- 调用时使用
async/await获取异步返回的选中值
修改后的自定义BottomSheet代码
import 'package:chavara/src/utils/theme/app_fonts.dart'; import 'package:flutter/material.dart'; import '../utils/theme/app_colors.dart'; import 'basic_text.dart'; // 修改为返回Future<String>,支持异步返回选中值 Future<String> basicBottomSheet(BuildContext context, String heading, int initialValue) { List<FruitsList> fList = [ FruitsList(index: 1, name: "Mango"), FruitsList(index: 2, name: "Apple"), FruitsList(index: 3, name: "Banana"), FruitsList(index: 4, name: "Cherry"), FruitsList(index: 5, name: "Mango"), FruitsList(index: 6, name: "Apple"), FruitsList(index: 7, name: "Banana"), FruitsList(index: 8, name: "Cherry"), ]; // 利用showModalBottomSheet的返回值特性传递结果 return showModalBottomSheet<String>( context: context, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(20.0)), ), builder: (BuildContext context) { // 在内部维护选中状态,确保UI正确更新 return StatefulBuilder( builder: (context, setState) { int selectedIndex = initialValue; return SizedBox( height: 600, child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.fromLTRB(30, 40, 30, 10), child: SizedBox( width: double.infinity, child: BasicText( text: heading, textColor: AppColors.black, fontSize: 20, fontWeight: AppFonts.fontWeightSemiBold, ), ), ), Padding( padding: const EdgeInsets.fromLTRB(30, 0, 30, 10), child: Container(height: 1, color: AppColors.bottomSheetLine), ), Expanded( child: SingleChildScrollView( child: Column( children: fList.map((data) => RadioListTile( title: Text(data.name, style: const TextStyle(fontSize: 14)), groupValue: selectedIndex, value: data.index, onChanged: (val) { setState(() { selectedIndex = data.index; }); // 关闭BottomSheet并返回选中的名称 Navigator.pop(context, data.name); }, )).toList(), ), ), ), ], ), ); }, ); }, ).then((value) { // 处理用户直接关闭BottomSheet的情况,返回默认空字符串 return value ?? ""; }); } class FruitsList { String name; int index; FruitsList({required this.name, required this.index}); }
修改后的调用代码
// 标记函数为async,支持await获取异步结果 Future<void> register(BuildContext context) async { int initialValue = 0; // 使用await等待BottomSheet返回选中值 String item = await basicBottomSheet(context, "Bottom Dialogue", initialValue); setState(() { snack(item, AppColors.secondary, context); }); }
内容的提问来源于stack exchange,提问作者kapil tk
相关产品推荐
相关产品推荐

