【问题标题】:Flutter ProviderNotFoundException IssueFlutter ProviderNotFoundException 问题
【发布时间】:2022-11-14 10:20:29
【问题描述】:

我想在颤振项目中使用firebase auth。我是使用提供商。一切都很好,但我正面临与供应商的一个问题。

我的 IconButtonWidget

`

class SocialIconButton extends StatelessWidget {
  final String socialIcon;
  const SocialIconButton({Key? key, required this.socialIcon})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: context.dynamicWidth(20)),
      child: IconButton(
          onPressed: (() {
            final provider =
                Provider.of<GoogleSignInProvider>(context, listen: false);
            provider.login();
          }),
          icon: Image.asset(socialIcon)),
    );
  }
}

`

当我按下按钮时,我遇到了这个问题:ProviderNotFoundException(错误:无法在此 SocialIconButton 小部件上方找到正确的提供者

【问题讨论】:

  • 您是否在 main/MaterialApp 中包含提供程序?
  • 不,我没有。我应该如何包括

标签: flutter provider


【解决方案1】:

在使用提供程序之前,您需要在 main.dart 文件中对其进行初始化 像这样

void main() {
  runApp(
    /// Providers are above [MyApp] instead of inside it, so that tests
    /// can use [MyApp] while mocking the providers
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => GoogleSignInProvider()),
      ],
      child: const MyApp(),
    ),
  );
}

之后重建应用程序

【讨论】:

    【解决方案2】:

    用 MultiProvider 包装您的应用程序并提供类似的实例

    void main() {
      runApp(
        MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (_) => GoogleSignInProvider()),
          ],
          child: const MyApp(),
        ),
      );
    }
    

    更多关于provider。你也可以检查riverpod2

    【讨论】:

    • 这行得通。我会将其标记为解决方案。谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2021-11-27
    • 2021-01-20
    • 2020-02-20
    • 2021-06-06
    • 2021-03-27
    • 2019-01-23
    相关资源
    最近更新 更多