Home > OS >  LateInitializationError Flutter using SharedPreferences.then
LateInitializationError Flutter using SharedPreferences.then

Time:03-07

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

CodePudding user response:

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

  • Related