LateInitialization Error In Flutter main.dart

I am developing my app and I don’t know why this late Initialization error has come I use this same code in my other apps as well there I don’t face such error but in this main file the error is persisting and I have been trying for so long It doesn’t works. bool? userLoggedIn isn’t also working flutter doesn’t letting it used. Here is my main.dart file code. Also If anyone can tell me how can I handle 2 logins of app shared preferences that would be a lot helpful

void main() async {
  await Firebase.initializeApp();
  runApp(const MyApp());

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

  _MyAppState createState() => _MyAppState();

class _MyAppState extends State<MyApp> {
  late bool userLoggedIn;
  void initState() {

  getLoggedInState() async {
    await HelperFunctions.getUserLoggedInSharedPreference().then((value) {
      setState(() {
        userLoggedIn = value!;

  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Dashee',
        theme: ThemeData(
          primarySwatch: Colors.deepPurple,
        home: userLoggedIn ? const Dashboard() : Splash());

>Solution :

LateInitializationError means a variable declared using the late keyword was not initialized on the constructor

You declare this boolean variable:

late bool userLoggedIn

but did not declare a constructor, so it won’t be initialized, the obvious thing to do is giving it a value on the constructor, like so:

_MyAppState() {
  userLoggedIn = false; // just some value so dart doesn't complain.

However may I suggest you don’t do that and instead simply remove the late keyword?
Doing that, of course, will give you an error because userLoggedIn is never initialized, but you can fix that by giving it a default value straight on it’s declaration or on the constructor initialization:

bool userLoggedIn = false;


_MyAppState(): userLoggedIn = false;

note how on the second option I didn’t use the constructor’s body, you should only declare a variable late if you plan on initializing it on the constructor’s body.

This should solve the LateInitializationError that you are getting.

Leave a Reply