Ad

How To Use Shared Preferences Without An Async Method In Dart?

I want to show a text in a child of a container in flutter but first I have to use shared preference to get my value, i tried to use sharedprefernce in a different function but it show an error and says Future cant be assigned to Widget. how can i fix it?

 Container(
               child: _show(),
              height: 40,
              width: MediaQuery.of(context).size.width - 230,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                      color: Colors.black26,
                      blurRadius: 6,
                      offset: Offset(0, 2)),
                ],
              ),
            ),

in other function i have :

_show() async {
  final prefs = await SharedPreferences.getInstance();
  var myVar= prefs.getInt('key');
  
  return myVar;

}
Ad

Answer

In order to use an async method inside your widget you have to use Future Builder, which just puts your app "on hold" until your data arrives.

you can use it like this:

 Container(
              child: FutureBuilder(
              future: _show(),
              builder: (context, snapshot) { // snapshot is just the data returned from the method, to access it's data you use .data  
                if (snapshot.hasData) { // this is for null safety, since you are accessing saved data the first time you use your app you might not have anything stored, which returns null
                  return Container(Text(snapshot.data.toString())) // here I just return a simple Text widget with data
                }
                else { 
                  return Container();
                }
              }
          );,
              height: 40,
              width: MediaQuery.of(context).size.width - 230,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                      color: Colors.black26,
                      blurRadius: 6,
                      offset: Offset(0, 2)),
                ],
              ),
            ),
Ad
source: stackoverflow.com
Ad