Flutter DropDownButton选中后无法实时更新问题求助
问题根源:你当前的AlertDialog直接依赖HomePage的状态,调用HomePage的setState只会刷新HomePage本身,已经弹出的AlertDialog不会被重新构建,导致Dropdown选中状态无法即时更新。
解决方案:用StatefulBuilder包裹弹窗内容区域,让弹窗拥有独立的局部状态更新能力,选择Dropdown选项时调用弹窗内部的状态刷新方法,就能实时更新显示。
修改后的完整代码:
import 'package:flutter/material.dart'; import 'package:spar_radar/services/database_service.dart'; import 'package:flutter/services.dart'; import 'package:date_format_field/date_format_field.dart'; class HomePage extends StatefulWidget{ const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } const List<String> types = <String>['Expence', 'Income']; class _HomePageState extends State<HomePage> { final DatabaseService _databaseService = DatabaseService.instance; String? _transactionName = null; double? _transactionAmount = null; String? _transactionDate = null; String? _transactionType = types.first; @override Widget build(Object context) { return Scaffold( floatingActionButton: _addTransactionButton(), ); } Widget _addTransactionButton() { return FloatingActionButton(onPressed: () { showDialog(context: context, builder: (_) => AlertDialog( title: const Text('Add Transaction'), // 用StatefulBuilder包裹弹窗内容 content: StatefulBuilder( builder: (dialogContext, setStateDialog) { return Column( mainAxisSize: MainAxisSize.min, children: [ TextField( onChanged: (value,) { setState(() { _transactionName = value; }); }, decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "Name", hintText: 'Add The Name of the Transaction' ), ), TextField( onChanged: (value) { setState(() { _transactionAmount = double.parse(value); }); }, decoration: InputDecoration(labelText: "Amount", border: OutlineInputBorder(), hintText: 'Enter the amount here'), keyboardType: TextInputType.number, inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly ], ), DateFormatField( type: DateFormatType.type2, onComplete: (date){ setState(() { _transactionDate = date.toString(); }); } ), DropdownButton<String>( value: _transactionType, icon: const Icon(Icons.arrow_drop_down), onChanged: (String? newValue) { // 先更新全局状态,再触发弹窗局部刷新 setState(() { _transactionType = newValue; }); setStateDialog(() {}); }, items: types.map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text(value), ); }).toList(), ) ], ); }, ) )); }, child: const Icon( Icons.add, ) ); } }
关键修改说明:
- 通过
StatefulBuilder获取弹窗内部的状态刷新方法setStateDialog - 在Dropdown的
onChanged回调中,先更新HomePage的全局状态_transactionType,再调用setStateDialog触发弹窗内容重建,实现Dropdown选中状态的实时更新
内容的提问来源于stack exchange,提问作者Joncrafting
相关产品推荐
相关产品推荐

