首页 > 解决方案 > Flutter/Riverpod:UI 不更新 StateNotifierProvider 中的状态更改

问题描述

当我知道状态正在改变的事实时,我的应用程序的 UI 没有更新。我正在使用watchRiverpod 的方法来处理这个问题,但除非我进行热重载,否则更改不会生效。

我有一个类HabitListStateNotifier,其中包含从列表中添加/删除习惯的方法:

class HabitListStateNotifier extends StateNotifier<List<Habit>> {
  HabitListStateNotifier(state) : super(state ?? []);

  void startAddNewHabit(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (_) {
          return NewHabit();
        });
  }

  void addNewHabit(String title) {
    final newHabit = Habit(title: title);
    state.add(newHabit);
  }

  void deleteHabit(String id) {
    state.removeWhere((habit) => habit.id == id);
  }
}

这是提供者:

final habitsProvider = StateNotifierProvider(
  (ref) => HabitListStateNotifier(
    [
      Habit(title: 'Example Habit'),
    ],
  ),
);

以下是HabitList(未更新的 UI 部分)的实现方式:

class HabitList extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    final habitList = watch(habitsProvider.state);

    /////////////not updating/////////////
    return ListView.builder(
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemBuilder: (context, index) {
        return HabitCard(
          habit: habitList[index],
        );
      },
      itemCount: habitList.length,
    );
    /////////////not updating/////////////
  }
}

最后,HabitCard(由什么HabitList组成):

class HabitCard extends StatelessWidget {
  final Habit habit;

  HabitCard({@required this.habit});

  @override
  Widget build(BuildContext context) {

    /////////////function in question/////////////
    void deleteHabit() {
      context.read(habitsProvider).deleteHabit(habit.id);
    }
    /////////////function in question/////////////

    return Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(devHeight * 0.03),
      ),
      color: Colors.grey[350],
      elevation: 3,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              HabitTitle(
                title: habit.title,
              ),
              Consumer(
                builder: (context, watch, child) => IconButton(
                  padding: EdgeInsets.all(8),
                  icon: Icon(Icons.delete),

                  /////////////function in question/////////////
                  onPressed: deleteHabit,
                  /////////////function in question/////////////
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

当我按下 a 中的删除图标时HabitCard,我知道Habit它已从列表中删除,但更改并未反映在 UI 中。但是,当我进行热重载时,它会按预期消失。我在这里做错了什么?

标签: flutterdartflutter-providerriverpod

解决方案


我不知道这是否是处理事情的正确方法,但我想通了。在HabitListStateNotifier, foraddNewHabitdeleteHabit中,我将这行代码:添加到最后:state = state;它完全按照我想要的方式工作。


推荐阅读