You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用Provider将showTimePicker值存入ChangeNotifier模型列表

解决方案:使用Provider将选择的时间存入ChangeNotifier模型的列表

步骤1:完善GridWidgetModel的状态修改方法

在你的GridWidgetModel类中添加专门的时间添加方法,并且**必须调用notifyListeners()**来通知所有监听该模型的Widget更新状态:

class GridWidgetModel extends ChangeNotifier {
  List<TimeOfDay> selectedTimes = [];

  // 添加选中时间的方法
  void addSelectedTime(TimeOfDay time) {
    selectedTimes.add(time);
    notifyListeners(); // 触发状态更新通知
  }
}

步骤2:修改timePicker方法,通过Provider操作模型

在触发showTimePicker的方法中,通过Provider.of获取模型实例,调用新增的方法完成时间添加,注意设置listen: false(仅修改状态,无需监听变化):

Future<void> timePicker(BuildContext context) async {
  final TimeOfDay? pickedTime = await showTimePicker(
    context: context,
    initialTime: TimeOfDay.now(),
  );

  if (pickedTime != null) {
    // 获取GridWidgetModel实例
    final gridModel = Provider.of<GridWidgetModel>(context, listen: false);
    // 调用模型方法添加时间
    gridModel.addSelectedTime(pickedTime);
  }
}

关键注意事项

  • 确保你的Widget树顶层已通过ChangeNotifierProvider注册GridWidgetModel,例如:
void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => GridWidgetModel(),
      child: const YourAppRootWidget(),
    ),
  );
}
  • 不要直接修改模型中的selectedTimes列表,必须通过封装的方法操作,同时触发notifyListeners(),否则状态变化无法传递到UI。

内容的提问来源于stack exchange,提问作者szczodralama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:09:55