Flutter: could not find the Provider above FutureBuilder

143 Views Asked by At

I'm trying to navigate to a screen where depending on 3 factors:

  1. If the app has run before or not
  2. If the user is null or not
  3. If the email is verified or not.

import 'package:client/providers/auth_provider.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../screens/home_screen.dart';
import '../screens/login_screen.dart';

class Wrapper extends StatefulWidget {
  @override
  _WrapperState createState() => _WrapperState();
}

class _WrapperState extends State<Wrapper> {
  FirebaseAuth auth = FirebaseAuth.instance;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext ctx) {
    return FutureBuilder(
        future: hasAlreadyStarted(),
        builder: (ctx, snapshot) {
          return Provider.of<User>(ctx) != null &&
                  snapshot.data == true &&
                  AuthProvider().isEmailVerified
              ? HomeScreen()
              : LoginScreen();
        });
  }

  Future<bool> hasAlreadyStarted() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    try {
      if (prefs.getBool("hasRun") == null) {
        await AuthProvider().logout();
        setState(() {
          prefs.setBool("hasRun", true);
        });
        return true;
      } else {
        return true;
      }
    } catch (error) {
      setState(() {
        prefs.setBool("hasRun", null);
      });
      return false;
    }
  }
}

The screen works fine on it's own, but when i Navigate from a different screen it gives me the error.

Could not find the correct Provider<User> above this FutureBuilder<bool> Widget

Can you explain the error and give me a solution. Thanks :D

1

There are 1 best solutions below

0
On BEST ANSWER

I just needed to wrap the entire MaterialApp with the StreamProvider