不能从 FloatingActionButton 内部使用 context.read()

Can't use context.read() from inside FloatingActionButton

我正在使用 Riverpod + StateNotifier 作为我的状态管理解决方案,我想在按下 FloatingActionButton 时调用一个方法,但我无法使用 context.read() 访问提供程序。同样在我的 AppBar 中,我无法使用它。这是我的代码:

main.dart

void main() {
  runApp(ProviderScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

homepage.dart

final homeProvider = StateNotifierProvider<HomeNotifier, HomeState>(
    (ref) => getIt<HomeNotifier>());

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: HomePageAppBar(),
      body: ProviderListener<HomeState>(
        provider: homeProvider,
        onChange: (context, state) {
          state.errorMessage.fold(() {}, (error) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(error),
              ),
            );
          });
        },
        child: Consumer(builder: (context, watch, child) {
          final state = watch(homeProvider);
          if (state.isLoading)
            return Center(child: CircularProgressIndicator());
          return ListView.builder(
            itemCount: state.items.length,
            itemBuilder: (context, index) =>
                MyCard(playlist: state.items[index]),
          );
        }),
      ),
      floatingActionButton: CreateButton(),
    );
  }
}

create_button.dart

class CreateButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      child: Icon(
        Icons.add_rounded,
        size: 36.0,
      ),
      onPressed: () {
        // here I want to use context.read(homeProvider)
      },
    );
  }
}

但是,如果我不为 FloatingActionButton 创建一个单独的小部件,而是将它放在脚手架中,我可以使用 context.read.

仅当您正在使用的文件导入了 riverpod 时,才能从上下文中读取提供程序。仔细检查您的导入,希望就这样!