Fedy Belaid
Fedy Belaid

Reputation: 165

Can't get value correctly from shared preferences

I'm trying to save a value in the shared preferences in flutter then get it. But it's always returning null. The value is being retrieved from an API that is working fine in the backend.

Here is my code:

Method in which i'm getting the data from the api:

List<LastOrder>? lastOrders;
  var isLoaded3 = false;

  int od_id = 0;

    getLastOrderMethod() async {
        lastOrders = await RemoteService().getLastOrder(2);
        if (lastOrders != null) {
          setState(() {
            isLoaded = true;
          });
          return ListView.builder(
              itemCount: 1,
              itemBuilder: (BuildContext context, int index) {
                setState(() {
                  od_id = lastOrders![0].id;
                  print('getLastOrderMethod: $od_id');
                  saveIdOrder(od_id);
                });
                return;
              });
        }
      }

Method in which i'm trying to save the variable value in the shared preferences:

Future<bool> saveIdOrder(value) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    print('save: $od_id');

    return await sharedPreferences.setInt('order_id', value);
  }

Method in which i'm trying to get the variable value in the shared preferences:

static Future getIdOrder() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    final x = sharedPreferences.getInt('order_id');
    print('get: $x');

    return x;
  }


@override
  void initState() {
    // TODO: implement initState
    print('intial ${od_id}'); => 0
    getIdOrder(); => null
    getLastOrderMethod();
    super.initState();
  }

I'd be glad for any kind of help!

Upvotes: 0

Views: 73

Answers (2)

Fedy Belaid
Fedy Belaid

Reputation: 165

Solved the issue by doing all the logic inside the listView.builder(), then updated the variable value inside a setState()

Upvotes: 0

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63689

getIdOrder() is a future method, it will take some time to fetch the data. While initState cant be async method, you can use .then and inside it call setState to update the ui. but Using FutureBuilder will be best option.

late final future = getIdOrder();
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: FutureBuilder(
      future: future,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Text("${snapshot.data}"); // your widget
        }
        return CircularProgressIndicator();
      },
    ),
    floatingActionButton: FloatingActionButton(onPressed: () {}),
  );
}

More about using FutureBuilder

Upvotes: 2

Related Questions