0

i have two future methods

Future<List> getTrns(String token,int page,) async {

final response = await 
http.get(Uri.parse("api1/?params" ),
    headers:{
      ....
    });
final String t = response.body;
List list =jsonDecode(t)['data'];
return list;

}

Future<String> getstate(String code,String token,DateTime now) async {
DateTime start_date = new DateTime(now.year, now.month, now.day);
 String stat='';

final response = await 
http.get(Uri.parse("api2/?params" ),
   headers:{
     ...
   });
final String t = response.body;
 List l = jsonDecode(t)['data'];


if(l.length == 0){
   stat = "absent";
}else {
   stat = "present";
}

return stat;

}

this first methode will get the list of employee while the second one will use each employee code to find their state from another api.. the two functions are working fine but displaying them in an Datatable gave me an error of

 Instance of future<string> 

Only in the stat cell while other cells are working fine here's how i built the table

 body: Column( children: <Widget>[
        FutureBuilder<List>(
        future: getTrns(widget.token,widget.page),
        builder: (ctx,ss){
          if(ss.hasError){
            print("error");
          }
          if(ss.hasData){
            datalist=ss.data!;

            return SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    child: _createDataTable(),

                )
            );
          }else {
            return Center(child: CircularProgressIndicator());
          }
        }
      ),



      MaterialButton(onPressed: () {
        widget.page = widget.page+1;
        print(widget.page);
      },
        child: Text("Next"),
        color: Colors.blue,)
       ]
       )
       )
      );
      }

  DataTable _createDataTable() {
    return DataTable(columns: _createColumns(), rows: _createRows());
  }
  List<DataColumn> _createColumns() {
    return [
      DataColumn(label: Text('ID')),
      DataColumn(label: Text('Full Name')),
      DataColumn(label: Text('State'))
    ];
  }
  List<DataRow> _createRows() {
    return datalist
        .map((list) => DataRow(cells: [
      DataCell(
          Text(list['emp_code'].toString()),
           onTap: (){
             Navigator.of(context).push(
                 MaterialPageRoute(builder: (BuildContext context)=>Details(token: w idget.token, emp:list['emp_code'].toString())
            ));
      }
 ),
 DataCell(
     Text(list['first_name'].toString()+" "+list['last_name'].toString()),
     onTap: (){
     Navigator.of(context).push(
     MaterialPageRoute(builder: (BuildContext context)=>Details(token: widget.token, emp:list['emp_code'].toString())
     ));
     }
 ),
 DataCell(Text( getstate(list['emp_code'], widget.token, widget.now).toString() ),
 onTap: (){
   Navigator.of(context).push(
       MaterialPageRoute(builder: (BuildContext context)=>Details(token: widget.token, emp:list['emp_code'].toString())
       ));
 }
 )
    ]))
        .toList();
  }


 }

this is the result table screenshot

Edit1: new cell code cell code the error is random, sometimes in first celland sometimes in a different one first result another result

Salim Dziri
  • 21
  • 1
  • 7

2 Answers2

0

You will need another FutureBuilder around getstate just as you did with getTrns.

Your code already demonstrates that you know how to use one, so I will not bore you with it.

If you need a refresher: What is a Future and how do I use it?

You may want to put your Future, into a variable instead of directly refering to them in your FutureBuilders though, because you want to keep the same Future (or rather it's probably already existing result) when the user trigger a rebuild that has nothing to do with your data, for example by tilting the screen of their device or changing the size of their browser or desktop window.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • i am still a beginner with flutter, i tried another future builder but the problem is that the 2nd function needs to get the empcode from the first one over and over for each employee.. – Salim Dziri Feb 07 '22 at 10:11
  • can you help me with an example ? – Salim Dziri Feb 07 '22 at 10:11
  • I don't see the problem. It does get the code now, doesn't it? So put it inside a FutureBuilder. You can have multiple FutureBuilders just as you can have multiple buttons or texts. Give it a try and share any problems you have. Replace `Text( getstate(list['emp_code'], widget.token, widget.now).toString())` with a `FutureBuilder` that will build that text once the future completes. – nvoigt Feb 07 '22 at 10:14
  • i got an error (null check operator used on a null value) – Salim Dziri Feb 08 '22 at 07:35
  • Then don't use the `!` operator to lie to the compiler about the nullability of variables :) If you post your code, maybe we can help. Without code, that's impossible. – nvoigt Feb 08 '22 at 08:23
  • i edited my post with screenshots, the pronlem is the error is randomly generated, when i execute the codes many times : sometimes i got no error and sometimes i got an error randomly for exmaple (cell1 + cell3) , (cell4) , (all cells) , (no error) , (cell 2, cell 4, cell5) ...etc – Salim Dziri Feb 08 '22 at 09:48
  • You forgot `if(ss.hasData){` in your second FutureBuilder. – nvoigt Feb 08 '22 at 13:11
  • Now i used if has data like the 1st builder, Else show a circularprogressIndicator, when i run the app there is works fine except 1 random cell will have an infinit circle. i though that this cell have no data but when i run again a different cell will have an infinit circle – Salim Dziri Feb 08 '22 at 13:59
  • Well, that is because you need to actually read and apply the tips in my last paragraph. You need to put your Future into a variable and give that variable to the future builder, otherwise it will run from the start every time build is called. – nvoigt Feb 08 '22 at 14:13
-1

Try this

final Map<String, dynamic> t = response.body;
list =jsonDecode(t)['data'] as Map<String, dynamic>;
return list;
Saiful Islam
  • 429
  • 6
  • 11