flutterdartflutter-sharedpreference

I tried to get name from SharedPreferences method but when run code show null value in the console in flutter How to solve it?


In my code at the home page fetch user name from firestore database and that's display nicely in UI. I want pass that name to shared preference function and store there and use that name in another pages also.

At my previous question I have solved saving name to sharedpreference method but now I couldn't display .It's show null.

Console Screenshot: enter image description here

code

  @override
  void initState() {
    super.initState();
    getData();
    fetchName();
    storeName();
    getStoreName();
  }

  Future getStoreName() async {
    getNameFromSharedPreferences();
    print("name $displayName");
  }

  void storeName() {
    String displayName = '${user?.displayName}';
    saveNameToSharedPreferences(displayName);
  }

enter image description here

SharedPreferences code

import 'package:shared_preferences/shared_preferences.dart';

String? _displayName;

String? get displayName => _displayName;

Future saveNameToSharedPreferences(String displayName) async {
  final SharedPreferences sn = await SharedPreferences.getInstance();

  await sn.setString('displayName', displayName);
}

Future getNameFromSharedPreferences() async {
  final SharedPreferences sn = await SharedPreferences.getInstance();

  _displayName = sn.getString('displayName');
}

enter image description here

how to get name and display from SharedPreferences method?


Solution

  • Your function getNameFromSharedPreferences() is a future you need to await and then display the value of name

    Future getStoreName() async {
        await getNameFromSharedPreferences(); //👈 add await here
        print("name $displayName");
      }
    
    

    And make sure that name is stored in the sharedPreference by logging it out