Flutter中点击按钮时如何将按钮标题传递给Cubit?
实现方法
只需要给Cubit的按钮点击方法新增文本参数,点击时传入对应按钮的标题,同时在状态中存储选中的标题列表,即可满足后续提交需求,具体修改步骤如下:
1. 修改State类,新增选中标题存储字段
在ReportInitial中新增selectedReportTitles字段,用于持久化存储所有选中的按钮文本,方便后续提交接口时直接取用:
class ReportInitial extends ReportState { final List<bool> reports; final bool isEnabled; final List<XFile?> images; final String? comment; final bool isPhotoEnabled; // 新增:存储选中的按钮标题 final List<String> selectedReportTitles; ReportInitial({ this.comment, required this.images, required this.isEnabled, required this.reports, required this.isPhotoEnabled, required this.selectedReportTitles, }); }
2. 修改Cubit方法,新增文本参数与对应处理逻辑
给reportButton方法新增String类型的入参接收按钮文本,切换按钮选中状态时同步更新选中标题列表,emit新状态时携带最新的选中标题数据:
class ReportCubit extends Cubit<ReportState> { ReportCubit() : super( ReportInitial( images: [], isEnabled: false, reports: List.filled(3, false), isPhotoEnabled: false, selectedReportTitles: [], // 初始化空列表 ), ); final List<bool> reportsList = [false, false, false]; List<String> selectedReportTitles = []; bool isEnabledC = false; // 新增buttonText入参 void reportButton(int number, String buttonText) { reportsList[number] = !reportsList[number]; // 同步更新选中标题列表 if (reportsList[number]) { selectedReportTitles.add(buttonText); } else { selectedReportTitles.remove(buttonText); } isEnabledC = reportsList.contains(true); emit( ReportInitial( isEnabled: isEnabledC, reports: reportsList, selectedReportTitles: selectedReportTitles, // 补全原有字段,避免状态丢失 images: state.images, isPhotoEnabled: state.isPhotoEnabled, comment: state.comment, ), ); } }
3. 修改Widget层点击回调,传入对应按钮文本
在每个GestureDetector的onTap回调中,调用reportButton时把当前按钮的text作为第二个参数传入即可:
SizedBox( width: size.width / 3, child: GestureDetector( onTap: () { cubit.reportButton(0, 'Comment'); }, child: ReportButton( enabled: state.reports[0], svg: constants.Assets.comment, text: 'Comment', ), ), ), SizedBox( width: size.width / 3, child: GestureDetector( onTap: () { cubit.reportButton(1, 'Broken station'); }, child: ReportButton( enabled: state.reports[1], svg: constants.Assets.attention, text: 'Broken station', ), ), ), SizedBox( width: size.width / 3, child: GestureDetector( onTap: () { cubit.reportButton(2, 'Blocked station'); }, child: ReportButton( enabled: state.reports[2], svg: constants.Assets.blockedStation, text: 'Blocked station', ), ), ),
优化建议
可以提前把三个按钮的配置(索引、图标、文本)统一封装为常量列表,遍历生成按钮组件,避免重复硬编码文本导致传参和显示不一致的问题:
const reportButtonConfigs = [ (index: 0, svg: constants.Assets.comment, text: 'Comment'), (index: 1, svg: constants.Assets.attention, text: 'Broken station'), (index: 2, svg: constants.Assets.blockedStation, text: 'Blocked station'), ];
后续向服务端提交数据时,直接读取state.selectedReportTitles即可拿到所有选中的按钮标题。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

