Home > Software design >  I tried to get name from SharedPreferences method but when run code show null value in the console i
I tried to get name from SharedPreferences method but when run code show null value in the console i

Time:01-26

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?

CodePudding user response:

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

Future getStoreName() async {
    await getNameFromSharedPreferences(); //           
  • Related