如何在切换DropdownButton时变更对应的文本变量?
实现步骤:
- 在状态类中定义三个文本变量,便于状态更新时读取
- 通过下拉选中值与文本变量的对应关系,动态获取当前需要的message内容
- 将动态获取的内容传入目标组件的
message参数
修改后的完整代码:
import 'package:flutter/material.dart'; class DropDownButtonDifficultySettingsWidget extends StatefulWidget { DropDownButtonDifficultySettingsWidget({Key? key}) : super(key: key); @override State<DropDownButtonDifficultySettingsWidget> createState() => _DropDownButtonDifficultySettingsState(); } class _DropDownButtonDifficultySettingsState extends State<DropDownButtonDifficultySettingsWidget> { String dropdownValue = 'Medium'; // 定义三个文本变量 String easyDrop = 'All ok'; String mediumDrop = '1 problem'; String hardDrop = 'All not ok'; @override Widget build(BuildContext context) { // 根据选中值匹配对应的message内容 String currentMessage; switch(dropdownValue) { case 'Easy': currentMessage = easyDrop; break; case 'Medium': currentMessage = mediumDrop; break; case 'Hard': currentMessage = hardDrop; break; default: currentMessage = mediumDrop; // 设置默认值 } // 示例:将currentMessage传入需要的组件参数,这里以展示文本为例,你可替换为实际场景 return Column( children: [ Theme( data: ThemeData( splashColor: Colors.blue.withOpacity(0.4), ), child: DropdownButton<String>( value: dropdownValue, elevation: 8, alignment: Alignment.centerRight, iconDisabledColor: Colors.blue, iconEnabledColor: Colors.blue, underline: Container(height: 0), style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.w500), onChanged: (String? newValue) { setState(() { dropdownValue = newValue!; }); }, items: <String>['Easy', 'Medium', 'Hard'] .map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text(value), ); }).toList(), ), ), Text('当前message内容:$currentMessage'), ], ); } }
更简洁的映射方式(可选)
如果觉得switch语句繁琐,可以用Map建立选中值与文本的映射关系:
// 在状态类中定义映射表 final Map<String, String> messageMap = { 'Easy': 'All ok', 'Medium': '1 problem', 'Hard': 'All not ok', }; // 在build中直接获取当前message String currentMessage = messageMap[dropdownValue] ?? '1 problem';
内容的提问来源于stack exchange,提问作者Verc
相关产品推荐
相关产品推荐

