Home > front end >  LateInitialization Error In Flutter main.dart
LateInitialization Error In Flutter main.dart

Time:11-17

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

CodePudding user response:

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.

Regarding multiple log-ins

if you want to have three (or more!) log in states, I recommend you declare an enum of those states:

enum LogInState {
  LoggedOff,
  LoggedInAsRider,
  LoggedInAsUser,
}

In order to store said state in sharedPreferences, you could store them as integers:

Future<void> savedLoggedInState(LogInState state) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setInt('some key', state.index);
}

then to read said value from shared preferences:

Future<LogInState> getLoginState() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int index = prefs.getInt('some key') ?? 0;
  return LogInState.values[index];
}

finally to display each different log in state, you'd do something like this:

home: _getLogInScreen(),
[...]

Widget _getLogInScreen() {
  switch (userLogIn) {
    case LogInState.LoggedOff:
      return Splash();
    case LogInState.LoggedInAsRider:
      return RiderDashboard();
    case LogInState.LoggedInAsUser:
      return UserDashBoard();
  }
  // if you make a new log in state, you need to add it to the switch 
  // statement or it will throw an unimplemented error
  throw UnimplementedError();
}
  • Related