Home > front end >  Flutter Shared Preference in Text Widget
Flutter Shared Preference in Text Widget

Time:10-29

I have successfully saved SharedPreferences in my app but now i am trying to display the data in a Text Widget. This is my code

//profile details
  late String name;
  late SharedPreferences profileData;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initial();
  }
  void initial() async {
    profileData = await SharedPreferences.getInstance();
    setState(() {
      name = profileData.getString('name')!;
    });
  }

Then in my text widget i have done this

                             Text('$name',
                                  style: TextStyle(
                                    color:Colors.black,
                                    fontSize: 20.0,
                                    fontWeight: FontWeight.bold,
                                  )),

And i am getting this error

LateInitializationError: Field 'name' has not been initialized.

what have i done wrong and how can i fix it

CodePudding user response:

I suspect here the problem is the initial build (the text value is a required parameter for a text field, which cannot be null). Try something like this:

Text(name ?? '',
  style: TextStyle(
  color:Colors.black,
  fontSize: 20.0,
  fontWeight: FontWeight.bold,
  )),

CodePudding user response:

This is because setState() is only triggered after the build is completed, meaning that the Text widget gets built with an uninitialised name. For this purpose it would be best if you instead did either

Option A:

var name = '';
late SharedPreferences profileData;

Option B:

String? name;
late SharedPreferences profileData;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initial();
  }
  void initial() async {
    profileData = await SharedPreferences.getInstance();
    setState(() {
      name = profileData.getString('name')!;
    });
  }

with

 Text(name ?? '',
       style: TextStyle(
       color:Colors.black,
       fontSize: 20.0,
       fontWeight: FontWeight.bold,
     )),
  • Related