Flutter问题:Product Dropdown onChange更新TextField值仅hover时可见
问题解决:禁用的TextField不随Controller更新立即刷新
问题原因
当TextField设置为enabled: false时,它不会主动监听TextEditingController的文本变化来触发重绘,只有在用户交互(比如hover)时才会更新UI显示。
解决方案
方案1:在StatefulWidget中调用setState强制刷新
修改onChange方法,赋值后触发UI重绘:
void onChange<Product>(prod) { BlocProvider.of<InvoiceCubit>(context).updateProduct(prod); categoryController.text = prod.category.categoryName.toString(); setState(() {}); // 强制触发组件重绘 }
方案2:用ValueListenableBuilder包裹TextField
通过监听controller的变化自动更新TextField,无需手动触发重绘:
var productCategory = Column( children: [ ValueListenableBuilder<TextEditingValue>( valueListenable: categoryController, builder: (context, value, child) { return TextField( controller: categoryController, enabled: false, focusNode: categoryFocusNode, ); }, ), const Padding( padding: EdgeInsets.all(5.0), child: SizedBox(width: 200)), ], );
方案3:替换为Text组件(仅展示场景)
如果TextField仅用于展示文本、无需编辑功能,直接用Text组件更简洁:
var productCategory = Column( children: [ Text( categoryController.text, style: TextStyle(color: Colors.grey[600]), // 模拟禁用TextField的视觉样式 ), const Padding( padding: EdgeInsets.all(5.0), child: SizedBox(width: 200)), ], );
内容的提问来源于stack exchange,提问作者NothingBox
相关产品推荐
相关产品推荐

