0

even after i have intitialized there is an error :

Late initialization error displayName

here is the code where i have set the value:

    var displayName=jsondata["username"];
    SharedPreferences prefs=await SharedPreferences.getInstance();
    prefs.setString('displayName', displayName);

and in here is i am accesing the data:

 late String displayName;

  getData() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  displayName=prefs.getString('displayName')?? "0";
  }

  initState() {
   getData();
   super.initState();
   }

and i dont know what is the issue? but on other screens it is working.

  • 1
    I thinks its better if you put empty value in `displayName`, so `String displayName = ""` – Ananda Pramono Dec 22 '21 at 04:24
  • I think that the problem is in displayName initState finishing before getData finishes. Try to add default value to displayName and remove late modifier. Moreover, add .then and set state to displayName. I think it will work. Read this: https://stackoverflow.com/questions/51901002/is-there-a-way-to-load-async-data-on-initstate-method – Atamyrat Babayev Dec 22 '21 at 04:48

1 Answers1

1

hope it work :)
create a class userpreferences and initialize shared preferences.

class UserPreferences {
  static SharedPreferences? _preferences;

  static const _keyDisplayName = 'displayName';
  static Future init() async => _preferences = await SharedPreferences.getInstance();

  static Future setDisplayName(String displayName) async => await _preferences!.setString(_keyDisplayName, displayName);
  static String? getDisplayName() => _preferences!.getString(_keyDisplayName);
}

then initialize userPreferences methood in your main.dart file
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await UserPreferences.init();
  runApp(const MyApp());
}

then call displayname from class userPreferences
late String displayName;

  @override
  void initState() {
    displayName = UserPreferences.getDisplayName() ?? "user name is null";
    super.initState();
  }
raghav042
  • 679
  • 6
  • 14