How can i access a variable outside a future function in flutter

Viewed 44

This is where my widget starts, i am fetching items from a url in another file then calling it in this dart file. This fetched items are the ones displaying on the screen. What i want is to update the state of the item.id which is stored in current id.

Future<List<Items>> list =  fetchItems();
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      
      // drawer: navdrawer(),

      backgroundColor: Colors.black,

      extendBody: true,
      body: Center(

        child: FutureBuilder(
          future: list,
          
          builder: (context, AsyncSnapshot snapshot)
          {
            if(snapshot.hasData)
              {
                return ListView.builder(
                  
                  itemCount: snapshot.data!.length,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, index){
                    Items item = snapshot.data[index];

                    String currentid = item.id;

This button has an onpress that has a set state that is supposed to update the item.id. This item.id is outside this future and thats the problem because it wount update it but it can print out the id

onPressed: () {
    setState(() {

        Future prevday() async {
            var i = int.parse(currentid);

            var nextnum = i + value2--;
            var sstring = nextnum.toString();

            var url = Uri.parse('https://insia.co.ke/test/nextday.php');
            var response = await http.post(url, body: {
            'day' : sstring,
            });

            var data2 = json.decode(response.body);
            // return data2[0];
        
            currentid = data2[0]['id'];
            var date = data2[0]['date'];
            var fajr = data2[0]['fajr'];
            var dhuhr = data2[0]['dhuhr'];
            var asr = data2[0]['asr'];
            var maghrib = data2[0]['maghrib'];
            var isha = data2[0]['isha'];
            var pic = data2[0]['pic'];
            var status = data2[0]['status'];
            var lunar = data2[0]['lunar'];
            var idate = data2[0]['idate'];

            // how can i access the above variables outside the future 
            // if i try the print outside the future it throws an error 
            //of cuurent id is undefined and the same for the other variables 
            print(currentid);

        }

        prevday();
    
    });
},
0 Answers
Related