Flutter:如何在普通Dart类中创建、使用及更新变量/状态?
解决方案
核心问题分析
你当前的代码中,_simulation列表是在Faith类初始化时创建的,eventTitle里的childsName只会取初始化时的固定值。后续修改childsName时,已经生成的Events实例不会自动更新标题,这是导致状态不同步的原因。
方案一:动态生成事件内容
不要在类初始化时固定事件列表,而是通过方法动态生成,确保每次获取事件时都使用最新的变量值:
class Faith { String? childsName = "Joe"; // 每次调用都会用当前childsName生成事件列表 List<Events> getSimulationEvents() { return [ Events( eventCode: 0, eventTitle: "Welcome ${childsName}, to the world of darkness.", eventImage: "assets/images/welcoming.jpg", choices: [ Choice(choiceText: "Continue"), Choice(choiceText: "Go Back"), ], ), ]; } // 更新名字的方法 void updateChildsName(String newName) { childsName = newName; // 若需UI同步更新,需结合状态管理工具触发重建 } }
使用时,每次需要事件列表都调用getSimulationEvents(),就能拿到带最新名字的标题。
方案二:给普通类添加状态通知能力
让Faith类继承ChangeNotifier,实现状态变化时的通知机制,结合Flutter状态管理工具(Provider/Riverpod)实现UI联动:
1. 修改Faith类
import 'package:flutter/foundation.dart'; class Faith extends ChangeNotifier { String? childsName = "Joe"; late List<Events> _simulation; Faith() { // 初始化事件列表 _refreshSimulation(); } // 刷新事件内容(使用当前childsName) void _refreshSimulation() { _simulation = [ Events( eventCode: 0, eventTitle: "Welcome ${childsName}, to the world of darkness.", eventImage: "assets/images/welcoming.jpg", choices: [ Choice(choiceText: "Continue"), Choice(choiceText: "Go Back"), ], ), ]; } // 对外暴露事件列表 List<Events> get simulation => _simulation; // 更新名字并通知UI void updateChildsName(String newName) { childsName = newName; _refreshSimulation(); // 通知所有监听者状态变化,触发UI重建 notifyListeners(); } }
2. 结合Riverpod使用
// 定义Faith的Provider final faithProvider = ChangeNotifierProvider((ref) => Faith()); // 在Widget中使用 class YourScreen extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final faith = ref.watch(faithProvider); final events = faith.simulation; return Column( children: [ TextField( onChanged: (value) { // 更新名字 ref.read(faithProvider).updateChildsName(value); }, ), Text(events[0].eventTitle), ], ); } }
3. 可选:直接更新已有事件属性
如果不想每次都重新生成事件列表,可以直接修改Events实例的标题(需确保eventTitle不是final):
// 修改Events类,允许修改eventTitle class Events { final int eventCode; String eventTitle; // 去掉final final String eventImage; final List<Choice> choices; Events({ required this.eventCode, required this.eventTitle, required this.eventImage, required this.choices, }); } // 修改Faith的update方法 void updateChildsName(String newName) { childsName = newName; if (_simulation.isNotEmpty) { _simulation[0].eventTitle = "Welcome ${childsName}, to the world of darkness."; } notifyListeners(); }
关键要点
- 普通Dart类的变量要和UI联动,必须具备状态通知能力(如
ChangeNotifier),否则UI无法感知变量变化。 - 动态生成事件或主动更新事件属性,是确保内容和变量同步的两种核心方式。
- 结合状态管理工具时,要通过
watch/Provider.of监听状态变化,触发UI重建。
内容的提问来源于stack exchange,提问作者enessol
相关产品推荐
相关产品推荐

