Home > Net >  How to use Future<string> in a dataTable in flutter
How to use Future<string> in a dataTable in flutter

Time:02-07

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

CodePudding user response:

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.

CodePudding user response:

Try this

final Map<String, dynamic> t = response.body;
list =jsonDecode(t)['data'] as Map<String, dynamic>;
return list;
  •  Tags:  
  • Related