Search code examples
flutterdartsharedpreferences

LateInitializationError: Field 'displayName' has not been initialized in Flutter's Shared Prefrence?


I am creating an Flutter application in which i need to store the user information and for some extent i am able to achieve it with Shared Prefrence.

i am storing the data at login screen as follows:

    var displayName=jsondata["username"];
    SharedPreferences prefs=await SharedPreferences.getInstance();
    prefs.setString('displayName', displayName);

and on my drawerScreen i am getting the same data as follows:

 late String displayName;
 initState() {
  getData();
  super.initState();
 }
 getData() async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  displayName=prefs.getString('displayName')!;
 }

but whenever i click on drawer button there is an error as shown:

LateInitializationError: Field 'displayName' has not been initialized.

but when i hot reload my app while drawer is opened there is no error when i go to other screen and get back to drawer the LateInitialization errro arises,

i dont know what causing this error

here is the How error arises

and this is the other screen where i am shifting from drawer:

 late String displayName;

getData() async {
   SharedPreferences prefs = await SharedPreferences.getInstance();
  displayName=prefs.getString('displayName')!;
  print(displayName);
  }  

initState() {
   getData();
   super.initState();
 }

     @override
    Widget build(BuildContext context) {
    return Scaffold(
    backgroundColor: Theme.of(context).backgroundColor,
     key: _scaffoldKey,
     drawer: SizedBox(
       width: MediaQuery.of(context).size.width * 0.75 < 400 ? 
     MediaQuery.of(context).size.width * 0.75 : 350,
       child: Drawer(
       child: AppDrawer(
        selectItemName: 'Home',
      ),
    ),
  ),
  appBar: AppBar(
    backgroundColor: Theme.of(context).scaffoldBackgroundColor,
    automaticallyImplyLeading: false,
    title: Row(
      children: <Widget>[
        SizedBox(
          height: AppBar().preferredSize.height,
          width: AppBar().preferredSize.height + 40,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              alignment: Alignment.centerLeft,
              child: GestureDetector(
                onTap: () {
                  _scaffoldKey.currentState!.openDrawer();
                },
                child: Icon(
                  Icons.dehaze,
                  color: Theme.of(context).textTheme.headline6!.color,
                ),
              ),
            ),
          ),
        ),

      ],
    ),
  ),

can someone suggest me a better way of doing it . Thanks in advance <3


Solution

  • I forgot to to add setState();

    late String displayName;
    initState() {
    getData();
    super.initState();
     }
     Future getData() async{
     SharedPreferences prefs = await SharedPreferences.getInstance();
     setState(() {
      displayName=prefs.getString('displayName')!;
      });
    
    }