Firebase Dart 尝试读取在创建其值期间抛出的提供程序

发布于 2025-01-15 09:08:09 字数 3592 浏览 3 评论 0原文

我现在正在开发一个身份验证系统,我遇到了这个错误:


Bad state: Tried to read a provider that threw during the creation of its value.
The exception occurred during the creation of type AuthenticationService.

这是我的 main.dart:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:twofound/authentication.dart';
import 'package:twofound/database.dart';
import 'package:twofound/swipe.dart';
import 'package:twofound/map.dart';
import 'package:twofound/offers.dart';
import 'package:twofound/friends.dart';
import 'package:twofound/profile.dart';
import 'package:twofound/splash.dart';
import 'package:twofound/login.dart';
import 'package:twofound/register.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MainSeite());
  await Firebase.initializeApp();
  connectToFireBase();
}

class MainSeite extends StatefulWidget {
  const MainSeite({Key? key}) : super(key: key);

  @override
  _MainSeiteState createState() => _MainSeiteState();
}

class _MainSeiteState extends State<MainSeite> {
  int currentIndex = 0;
  List<Widget> pages = [
    const RegisterForm(),
    const Swipe(),
    const Map(),
    const Chat(),
    const Contacts(),
    const Profile(),
  ];

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          Provider<AuthenticationService>(
            create: (_) => AuthenticationService(FirebaseAuth.instance),
          ),
          StreamProvider(
            create: (context) =>
                context.read<AuthenticationService>().authStateChanges,
            initialData: null,
          ),
        ],
        child: MaterialApp(
          home: Scaffold(
            bottomNavigationBar: BottomNavigationBar(
              backgroundColor: Colors.black,
              selectedItemColor: Colors.orange,
              unselectedItemColor: Colors.black,
              currentIndex: currentIndex,
              items: [
                BottomNavigationBarItem(
                    icon: Icon(Icons.people), label: "Swipe"),
                BottomNavigationBarItem(icon: Icon(Icons.map), label: "Map"),
                BottomNavigationBarItem(
                    icon: Icon(Icons.zoom_in_outlined),
                    label: "Activity Offers"),
                BottomNavigationBarItem(icon: Icon(Icons.chat), label: "Social")
              ],
              onTap: (index) {
                setState(() {
                  currentIndex = index;
                });
              },
            ),
            body: SafeArea(child: pages[currentIndex]),
          ),
        ));
  }
}

class AuthenticationWrapper extends StatelessWidget {
  const AuthenticationWrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final firebaseUser = context.watch<User?>();
    if (firebaseUser == null) {
      return const RegisterForm();
    }
    return const MainSeite();
  }
}

void connectToFireBase() async {
  final FirebaseAuth authenticate = FirebaseAuth.instance;
  UserCredential result = await authenticate.signInAnonymously();
  User user = result.user!;

  DatabaseService database = DatabaseService(user.uid);

  database.setEntry("Test", "test text");
}

我希望用户在退出 Firebase 时看到注册页面,在登录时看到主页。我使用可能导致该错误的提供商。

如果你能帮助我,我非常高兴,因为我是 dart 和 flutter 的新手。

I'm working on a authentication system right now, and I'm facing this error:


Bad state: Tried to read a provider that threw during the creation of its value.
The exception occurred during the creation of type AuthenticationService.

This is my main.dart:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:twofound/authentication.dart';
import 'package:twofound/database.dart';
import 'package:twofound/swipe.dart';
import 'package:twofound/map.dart';
import 'package:twofound/offers.dart';
import 'package:twofound/friends.dart';
import 'package:twofound/profile.dart';
import 'package:twofound/splash.dart';
import 'package:twofound/login.dart';
import 'package:twofound/register.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MainSeite());
  await Firebase.initializeApp();
  connectToFireBase();
}

class MainSeite extends StatefulWidget {
  const MainSeite({Key? key}) : super(key: key);

  @override
  _MainSeiteState createState() => _MainSeiteState();
}

class _MainSeiteState extends State<MainSeite> {
  int currentIndex = 0;
  List<Widget> pages = [
    const RegisterForm(),
    const Swipe(),
    const Map(),
    const Chat(),
    const Contacts(),
    const Profile(),
  ];

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          Provider<AuthenticationService>(
            create: (_) => AuthenticationService(FirebaseAuth.instance),
          ),
          StreamProvider(
            create: (context) =>
                context.read<AuthenticationService>().authStateChanges,
            initialData: null,
          ),
        ],
        child: MaterialApp(
          home: Scaffold(
            bottomNavigationBar: BottomNavigationBar(
              backgroundColor: Colors.black,
              selectedItemColor: Colors.orange,
              unselectedItemColor: Colors.black,
              currentIndex: currentIndex,
              items: [
                BottomNavigationBarItem(
                    icon: Icon(Icons.people), label: "Swipe"),
                BottomNavigationBarItem(icon: Icon(Icons.map), label: "Map"),
                BottomNavigationBarItem(
                    icon: Icon(Icons.zoom_in_outlined),
                    label: "Activity Offers"),
                BottomNavigationBarItem(icon: Icon(Icons.chat), label: "Social")
              ],
              onTap: (index) {
                setState(() {
                  currentIndex = index;
                });
              },
            ),
            body: SafeArea(child: pages[currentIndex]),
          ),
        ));
  }
}

class AuthenticationWrapper extends StatelessWidget {
  const AuthenticationWrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final firebaseUser = context.watch<User?>();
    if (firebaseUser == null) {
      return const RegisterForm();
    }
    return const MainSeite();
  }
}

void connectToFireBase() async {
  final FirebaseAuth authenticate = FirebaseAuth.instance;
  UserCredential result = await authenticate.signInAnonymously();
  User user = result.user!;

  DatabaseService database = DatabaseService(user.uid);

  database.setEntry("Test", "test text");
}

I want the user to see the register Page when logged out of Firebase and the Main Page when logged in. I used providers for this which are probably causing the error.

I'm very happy if you could help me because I'm new to dart and flutter.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空城旧梦 2025-01-22 09:08:09

如果没有 AuthenticationService 的源代码,就不可能说出导致异常的原因。请将其添加到您的问题中。另外,对于未来的问题,请考虑将问题范围缩小到似乎导致问题的最小代码位。但是,至少提供最小的、可重现的示例

编辑:

AuthenticationService 的源看起来不错。异常来自 StreamProvider.create。这是在当前 BuildContext 中 authService 可用之前调用的 ctx.read 。像这样确定提供商的范围可以消除这个问题。

  @override
  Widget build(BuildContext context) {
    return Provider(
      create: (_) => AuthenticationService(FirebaseAuth.instance),
      child: StreamProvider(
          create: (ctx) => ctx.read<AuthenticationService>().authStateChanges,
          initialData: null,
          child: MaterialApp(),
      ),
    );
  }

It's impossible to say what caused the exception without the source for AuthenticationService. Please add it to your question. Also for future questions consider narrowing down the problem to the smallest bit of code that seems to be causing the problem(s). However, provide at least Minimal, Reproducible Example.

Edit:

Source for AuthenticationService looks ok. The exception is coming from StreamProvider.create. Here is ctx.read called before authService is available in current BuildContext. Scoping providers like this eliminates this problem.

  @override
  Widget build(BuildContext context) {
    return Provider(
      create: (_) => AuthenticationService(FirebaseAuth.instance),
      child: StreamProvider(
          create: (ctx) => ctx.read<AuthenticationService>().authStateChanges,
          initialData: null,
          child: MaterialApp(),
      ),
    );
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文