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
The way you instantiating
sharedPreferences = await SharedPreferences.getInstance();needs to wait for instance ofSharedPreferences. The easiest way is to use FutureBuilder to wait, something like:Also, you can handle it as you want. The main idea is to wait for the instance creation.