简体   繁体   中英

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 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 {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

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

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

class _MyAppState extends State<MyApp> {
  late bool userLoggedIn;
  @override
  void initState() {
    getLoggedInState();
    super.initState();
  }

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

  @override
  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());
  }
}
  

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;

or

_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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM