尝试根据文档使用 StateNotifierProvider

Trying to use StateNotifierProvider as per documentation

分别阅读 ConsumerWidgetStateNotifierProvider 的 flutter_riverpod 和 riverpod 文档后,我对示例代码进行了如下修改:

这是我的 StateNotifier class:

class SelectedFoodsNotifier extends StateNotifier<List<Food>> {
  SelectedFoodsNotifier() : super([]);

  void add(Food food) {
    state = [...state, food];
  }

  void remove(int foodId) {
    state = [
      for (final food in state)
        if (food.id != foodId) food,
    ];
  }
}

这是我的提供商:

final selectedFoodsProvider = StateNotifierProvider((ref) => SelectedFoodsNotifier());

这是我的 ConsumerWidget class:

import 'package:diabretes/providers/providers.dart';
import 'package:diabretes/respository/DatabaseRepository.dart';
import 'package:diabretes/widgets/FoodCalculator/no_foods_selected.dart';
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

class CalculatorDrawer extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    List<Food> selected_foods = watch(selectedFoodsProvider);

    return AnimatedContainer(
        duration: Duration(milliseconds: 500),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10.0),
            topRight: Radius.circular(10.0),
          ),
          boxShadow: [
            BoxShadow(
                offset: Offset(0, 0),
                color: Colors.black.withOpacity(0.20),
                blurRadius: 16,
                spreadRadius: 2)
          ],
        ),
        child: NoFoodsSelected());
  }
}

但是线

List<Food> selected_foods = watch(selectedFoodsProvider);

出现以下错误:The argument type 'StateNotifierProvider<SelectedFoods, dynamic>' can't be assigned to the parameter type 'ProviderBase<Object?, List<Food>>'

我错过了什么?

提前致谢。

尝试final selectedFoodsProvider = StateNotifierProvider<SelectedFoodsNotifier, List<Food>>((ref) => SelectedFoodsNotifier());

StateNotifierProvider 采用两个通用参数。

像这样输入您的提供者是否有帮助?

final StateNotifierProvider<SelectedFoodsNotifier, List<Food>> selectedFoodsProvider = StateNotifierProvider((ref) => SelectedFoodsNotifier());

我强调始终明确输入我的提供者以避免在使用我的提供者时出现输入错误。