skip to Main Content

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!

2

Answers


  1. Chosen as BEST ANSWER

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


  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search