Flutter - initialize Firebase and check if internet connection, but not in the right order

425 Views Asked by At

I am trying to setup some check before the user can get access to his data.

I would like first to check if there is an internet connection. If so, then and only then I want to await Firebase.initializeApp();

But right now, I am not able to setup all this properly. Here is the code. If you could comment to help me it would be great. Thank you.

bool hasInternet = false;

Future main() async {

  WidgetsFlutterBinding.ensureInitialized();

  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  await Firebase.initializeApp();

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

  @override
  Widget build(BuildContext context) => ChangeNotifierProvider(
     create: (context)=> EventProvider(),

     child:LayoutBuilder(
      builder: (context, constraints){
        return OrientationBuilder(
          builder: (context, orientation) {
            SizeConfig().init(constraints, orientation);

            return MaterialApp(
                title: "",
                home:  const MainPage(),
                theme: ThemeData(primarySwatch: Colors.blue),

                routes: {
                  "/today": (context) => const Today_Home(),
                  "/agenda": (context) => const AgendaOrganize(),
                  
                }
            );
          },
        );
      },
    ));
  }

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

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {

  late StreamSubscription subscription;
  late StreamSubscription internetSubscription;
  bool hasInternet = false;
  ConnectivityResult result = ConnectivityResult.none;
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();

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

    subscription = Connectivity().onConnectivityChanged.listen((result) {
      setState(() => this.result = result);
    });

    internetSubscription =
        InternetConnectionChecker().onStatusChange.listen((status) {
          final hasInternet = status == InternetConnectionStatus.connected;

          setState(() => this.hasInternet = hasInternet);

          if (hasInternet != true) {
            showSnackBarMsg(context, noInternet,10);
          } else {return;}

        });
  }

  @override
  void dispose() {
    subscription.cancel();
    internetSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initialization,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Scaffold(
            body: Center(
              child: Text("Error: ${snapshot.error}"),
            ),
          );
        }

        if (snapshot.connectionState == ConnectionState.done) {
          return StreamBuilder(
            stream: FirebaseAuth.instance.authStateChanges(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.active) {
                Object? user = snapshot.data;
                if (user == null) {
                  return const LoginSignupScreen(); ///If user not connected => go to login screen
                }
                else {
                  return const Today_Home();  ///Else, go to Today_Home Page
                }
              }
              return const Scaffold(
                body: Center(
                  child: Text("Checking Login..."),
                ),
              );
            },
          );
        }
        return const Scaffold(
          body: Center(
            child: Text("Connecting to the app..."),
          ),
        );
      },
    );
  }
}

0

There are 0 best solutions below