Firebase Dart Tried to read a provider that threw during the creation of its value

Viewed 196

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.

1 Answers

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(),
      ),
    );
  }
Related