Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

LateInitializationError Flutter using SharedPreferences.then

I want set value of bool v from SharedPreferences in flutter but getting LateInitializationError.

here’s my code:

import 'package:agl_mdd/home/home.dart';
import 'package:agl_mdd/start.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {

    late bool v;

    bool getIsForFirstTime() {
      SharedPreferences.getInstance().then((value) {
        if (value.get('isBank') != null){
          v = true;
        }else {
          v = false;
        }
      });
      return v;
    }

    return MaterialApp(
      title: 'App...',
      theme: ThemeData(
      ),
      debugShowCheckedModeBanner: false,
      home: getIsForFirstTime() ? const Home(wholeDataList: []) : const Start(),
    );
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that you’re returning the value of v before then is executed.
I would recommend to make all of this logic in main method and then, give the resulting boolean to MyApp

Future<void> main() async{
  WidgetsFlutterBinding.ensureInitialized();
  final v = await getIsForFirstTime();
  runApp( MyApp(firstTime: v,));
}


    Future<bool> getIsForFirstTime() async{
      final sharedPrefs=await SharedPreferences.getInstance();
      
      return sharedPrefs.get('isBank') != null;
    }
class MyApp extends StatelessWidget {
  const MyApp({Key? key,required this.firstTime,}) : super(key: key);
final bool firstTime;
  @override
  Widget build(BuildContext context) {

    

    return MaterialApp(
      title: 'App...',
      theme: ThemeData(
      ),
      debugShowCheckedModeBanner: false,
      home: firstTime ? const Home(wholeDataList: []) : const Start(),
    );
  }
}

This is a waaay more clean code and easier to read. Note that the WIdgetsFlutterBinding is necessary in order to make main method a Future

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading