0

I am having a error The method 'getString' was called on null. Receiver: null Tried calling: getString("name") I already instantiated

firebaseFirestore = FirebaseFirestore.instance;
  sharedPreferences = await SharedPreferences.getInstance();
class _HomePageState extends State<HomePage> {
  HomepageBloc _bloc;
  ScrollController _scrollController = ScrollController();
  TextEditingController _userNameSearchController = TextEditingController();
  String userName = sharedPreferences.getString(SharedPreferencesKey.name);
  String userToken = sharedPreferences.getString(SharedPreferencesKey.token);
  @override
  void initState() {
    super.initState();
    _bloc = HomepageBloc(userToken);
  }

  @override
  void dispose() {
    super.dispose();
    _bloc.dispose();
  }

I don't know why I am getting this error, it would be wonderful if this error can be solved

Dijon
  • 103
  • 1
  • 7

2 Answers2

0

The way you instantiating sharedPreferences = await SharedPreferences.getInstance(); needs to wait for instance of SharedPreferences. The easiest way is to use FutureBuilder to wait, something like:

FutureBuilder(
        future: SharedPreferences.getInstance(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final sharedPreferences = snapshot.data;
            String userName = sharedPreferences.getString(SharedPreferencesKey.name);
            String userToken = sharedPreferences.getString(SharedPreferencesKey.token);
          }
        },
      )

Also, you can handle it as you want. The main idea is to wait for the instance creation.

Zah_ARin
  • 26
  • 1
  • 7
0

Define shared instance like this sharedPreferences = await SharedPreferences.getInstance(); and also add await to define the variable like

String userToken = await sharedPreferences.getString(SharedPreferencesKey.token);