我正在努力学习Flutter 动.我开始了"了解Flutter 翼的Firebase"教程.

我在本教程的第5步(添加RSVP功能)结束时收到Provider 错误. https://firebase.google.com/codelabs/firebase-get-to-know-flutter?authuser=0#4

将以下代码添加到HOPE_Page.dart文件中时,会出现以下错误.

谢谢.

// Add from here
          Consumer<ApplicationState>(
            builder: (context, appState, _) => AuthFunc(
                loggedIn: appState.loggedIn,
                signOut: () {
                  FirebaseAuth.instance.signOut();
                }),
          ),
// to here

希望页面dart

import 'package:firebase_auth/firebase_auth.dart' // new
   hide EmailAuthProvider, PhoneAuthProvider;    // new
import 'package:flutter/material.dart';           // new
import 'package:provider/provider.dart';          // new

import 'app_state.dart';                          // new
import 'src/authentication.dart';                 // new
import 'src/widgets.dart';

class HomePage extends StatelessWidget {
 const HomePage({super.key});

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: const Text('Firebase Meetup'),
     ),
     body: ListView(
       children: <Widget>[
         Image.asset('assets/codelab.png'),
         const SizedBox(height: 8),
         const IconAndDetail(Icons.calendar_today, 'October 30'),
         const IconAndDetail(Icons.location_city, 'San Francisco'),
         // Add from here
         Consumer<ApplicationState>(
           builder: (context, appState, _) => AuthFunc(
               loggedIn: appState.loggedIn,
               signOut: () {
                 FirebaseAuth.instance.signOut();
               }),
         ),
         // to here
         const Divider(
           height: 8,
           thickness: 1,
           indent: 8,
           endIndent: 8,
           color: Colors.grey,
         ),
         const Header("What we'll be doing"),
         const Paragraph(
           'Join us for a day full of Firebase Workshops and Pizza!',
         ),
       ],
     ),
   );
 }
}

错误代码:

This app is linked to the debug service: ws://127.0.0.1:59701/r_M_M0NpAZc=/ws
Debug service listening on ws://127.0.0.1:59701/r_M_M0NpAZc=/ws
Connecting to VM Service at ws://127.0.0.1:59701/r_M_M0NpAZc=/ws
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following ProviderNotFoundException was thrown building Consumer<ApplicationState>(dirty):
Error: Could not find the correct Provider<ApplicationState> above this Consumer<ApplicationState>
Widget

This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:

- You added a new provider in your `main.dart` and performed a hot-reload.
  To fix, perform a hot-restart.

- The provider you are trying to read is in a different route.

  Providers are "scoped". So if you insert of provider inside a route, then
  other routes will not be able to access that provider.

- You used a `BuildContext` that is an ancestor of the provider you are trying to read.

  Make sure that Consumer<ApplicationState> is under your MultiProvider/Provider<ApplicationState>.
  This usually happens when you are creating a provider and trying to read it immediately.

  For example, instead of:

  Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // Will throw a ProviderNotFoundError, because `context` is associated
      // to the widget that is the parent of `Provider<Example>`
      child: Text(context.watch<Example>().toString()),
    );
  }

  consider using `builder` like so:

  Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // we use `builder` to obtain a new `BuildContext` that has access to the provider
      builder: (context, child) {
        // No longer throws
        return Text(context.watch<Example>().toString());
      }
    );
  }


If none of these solutions work, consider asking for help on StackOverflow:
https://stackoverflow.com/questions/tagged/flutter

The relevant error-causing widget was:
  Consumer<ApplicationState>
  Consumer:file:///D:/flutter_projeler/flutter-codelabs/firebase-get-to-know-flutter/step_02/lib/home_page.dart:26:11

When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 294:3       throw_
packages/provider/src/provider.dart 343:7                                         _inheritedElementOf
packages/provider/src/provider.dart 293:30                                        of
packages/provider/src/consumer.dart 181:16                                        buildWithChild
packages/nested/nested.dart 259:41                                                build
packages/flutter/src/widgets/framework.dart 5541:22                               build
packages/nested/nested.dart 279:18                                                build
packages/flutter/src/widgets/framework.dart 5471:15                               performRebuild
packages/flutter/src/widgets/framework.dart 5187:7                                rebuild
packages/flutter/src/widgets/framework.dart 2895:18                               buildScope
packages/flutter/src/widgets/binding.dart 984:9                                   drawFrame
packages/flutter/src/rendering/binding.dart 457:5                                 [_handlePersistentFrameCallback]
packages/flutter/src/scheduler/binding.dart 1325:7                                [_invokeFrameCallback]
packages/flutter/src/scheduler/binding.dart 1255:9                                handleDrawFrame
packages/flutter/src/scheduler/binding.dart 1113:5                                [_handleDrawFrame]
lib/_engine/engine/platform_dispatcher.dart 1274:5                                invoke
lib/_engine/engine/platform_dispatcher.dart 248:5                                 invokeOnDrawFrame
lib/_engine/engine/initialization.dart 186:36                                     <fn>
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 574:37  _checkAndCall
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 579:39  dcall

════════════════════════════════════════════════════════════════════════════════════════════════════
Application finished.

Exited (-1).```

推荐答案

错误基本上是说Consumer Widget不在ProviderWidget内.

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final ToDoNotifier toDoNotifier = ToDoNotifier();
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => toDoNotifier,
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: ToDoListScreen(
          toDoNotifier: toDoNotifier,
        ),
      ),
    );
  }
}

通过使用ChangeNotifierProvider包装MaterialApp小部件,它允许您在整个小部件树中访问和共享特定类型的ChangeNotiizer.

Create属性是强制属性,可以使用任何名称创建一个新类,并使用"ChangeNotifier."扩展它,

class ToDoNotifier extends ChangeNotifier {
//add your data or functions
}

通过赋予类对象创建属性,您将能够访问对象中的任何内容,使用者基本上就像一个侦听器,如果提供者中有更改

希望这能帮上忙.

Flutter相关问答推荐

Flutter -如何从布局填充(对称水平)中排除小部件?

我如何才能动态地将小部件排成一排进行排列呢?

如何在Ffltter Chrome应用程序中使用webview_fltter_web显示自定义html而不是外部uri?

如何在默认情况下隐藏appBar并在向下滚动时显示它- Flutter

如何将Visual Studio代码中Flutter 应用的包名从com.example.XXX更改为Play Store中受限制的包名称

SingleChildScrollView在ErrorWidget.builder中不工作

Supabase Auth:重定向到 Google.com 而不是我的应用程序

如何使自动焦点位于已经有一些文本的 TextField 的第一行?

Flutter居中的SizedBox无法居中

无法使用 bloc 更新 ListView.builder 的特定时间

在向 Google Route API 发送 HTTP Post 请求期间发生错误,

应用程序和应用程序内的 webview 之间的单点登录

flutter 创建一个带有 2 个图标的按钮

如何限制用户每 24 小时执行的操作数?

仅使用 Flutter 在本地环境中托管 Web 服务器

如何在手势检测器中获得涟漪效应

我几乎每次都将 Stateless Widget 与 BLoC 一起使用.我错了吗?

带有 Dismissible 和 Provider (NotifyListener) 的笨拙动画

用于空值 FirebaseFirestore 的空值判断运算符

单击列表视图导航到 Flutter 中的另一个页面