-1

Hi I'm new to flutter and I'm struggling to use shared preference inside the builder method, Here is my code:

getId() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String sessionId = prefs.getString('sessionId');
      return Text(sessionId);
    }

This is a piece of my build method:

ListTile(
                  title: Text(
                    'Welcome, $getId()',
                    style: TextStyle(color: Colors.white),
                  ),

Here's the error output that I get for trying to use the shared pref inside a text widget:

dynamic function closure flutter
Machio
  • 13
  • 4

2 Answers2

0

You can use the FutureBuilder widget

Example:

FutureBuilder(
      future: getId(),
      builder: (context, snapshot) {
        if (snapshot.hasData){
          return ListTile(
              title: Text(
                'Welcome, ${snapshot.data}',
                style: TextStyle(color: Colors.white),
              ),
        }else if (snapshot.hasError){
          return Container(); //Error getting data
        }else{
          return Container(); //show Loading
        }
      },);

And in your getId() return String instead of a Text Widget Example:

getId() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String sessionId = prefs.getString('sessionId');
      return sessionId;
    }
Nishuthan S
  • 1,538
  • 3
  • 12
  • 30
0

call getId function in initState to assign value to the variable "id".

@override
 void initState() {
 super.initState();
 getId.then((value) => setState(() {
      id = value;
    }));
}

In your build method

  ListTile(
              title: Text(
                'Welcome, $id',
                style: TextStyle(color: Colors.white),
              ),

Your getId function will return string

getId() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String sessionId = prefs.getString('sessionId');
  return sessionId;
}
Bilal Aslam
  • 769
  • 6
  • 13