'late initilization error shared prefrences in flutter?

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.



Solution 1:[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();
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1