Home > Software design >  How to store data in shared preference when retrieve from database firestore in flutter?
How to store data in shared preference when retrieve from database firestore in flutter?

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.

Code

home page code ( initstate and send name to saveNameToSharedPreferences() method )

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

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

enter image description here

SharedPreferences code

import 'package:shared_preferences/shared_preferences.dart';

String? _displayName;

String? get displayName => _displayName;

Future saveNameToSharedPreferences() 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');
}

How to solve this ?

CodePudding user response:

You are calling function as an extension. Try to pass parameter instead.

Make the following changes

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

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

And call it as

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

  • Related