简体   繁体   中英

Future Builder not rendering data table

in want create table from api response.i created data.table using future builder. The future builder fires api twice not not return any data

class HomeScreen extends StatefulWidget {
 const HomeScreen({super.key});
 
 @override
 State<HomeScreen> createState() => _HomeScreenState();
}
 
class _HomeScreenState extends State<HomeScreen> {
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     body: FutureBuilder(
       future: unpaid(),
       builder: (context, snapshot) {
         if (snapshot.hasData) {
           return Container(
               padding: const EdgeInsets.all(5),
               child:
                   Dataclass(datalist: snapshot.data as List<UnpaidDetails>));
         } else {
           return Container(
 
               // padding: const EdgeInsets.all(5),
               // child: Dataclass(
               //     datalist: snapshot.data as List<UnpaidDetails>)
               );
         }
       },
     ),
   );
 }
 
 Future<String?> getToken() async {
   final SharedPreferences prefs = await SharedPreferences.getInstance();
   return prefs.getString('token');
 }
 
 Future<List<UnpaidDetails>> unpaid() async {
   String? token = await getToken();
 
   final response = await http.get(
       Uri.parse('https://test.url/api/unpaid'),
       headers: {
         'Content-Type': 'application/json',
         'Accept': 'application/json',
         'Authorization': 'Bearer $token',
       });
 
   if (response.statusCode == 200) {
     var result = jsonDecode(response.body);
     List jsonResponse = result["UnpaidDetails"] as List;
 
     return jsonResponse.map((e) => UnpaidDetails.fromJson(e)).toList();
   } else {
     throw Exception('Failed to update album.');
   }
 }
}
 
class Dataclass extends StatefulWidget {
 Dataclass({Key? key, required List<UnpaidDetails> this.datalist})
     : super(key: key);
 List<UnpaidDetails> datalist;
 @override
 DataclassState createState() {
   return DataclassState();
 }
}
 
class DataclassState extends State<Dataclass> {
 @override
 Widget build(BuildContext context) 
  return SingleChildScrollView(
       scrollDirection: Axis.vertical,
       child: FittedBox(
           child: DataTable(
         sortColumnIndex: 1,
         showCheckboxColumn: false,
         border: TableBorder.all(width: 1.0),
         columns: const [
           DataColumn(
               label: Text(
             "Period",
             style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
           )),
           DataColumn(
               label: Text(
             "Amount",
             style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
           )),
         ],
         rows: widget.datalist
             .map((data) => DataRow(cells: [
                   DataCell(
                     Text(data.month,
                         style: const TextStyle(
                             fontSize: 26, fontWeight: FontWeight.w500)),
                   ),
                   DataCell(
                     Text(data.price.toString(),
                         style: const TextStyle(
                             fontSize: 26, fontWeight: FontWeight.w500)),
                   ),
                 ]))
             .toList(),
       )));     }}

1 api call twice

api call fires twice the first one bring response. second one is send request without header and receive error. i am using jsontodart.in to create class. Help me execute future builder in clean way

For the non data problem:

Remove your getter:

get datalist => null;

declare a datalist variable in your Datatable class:

class Dataclass extends StatefulWidget {
  Dataclass({Key? key, required List<UnpaidDetails> this.datalist})
      : super(key: key);

  List<UnpaidDetails> datalist;

And read it from your state with

rows: widget.datalist

instead of

rows: datalist

And for your second call. You don't have to make a call in initstate. So you can delete your initstate method and change your future builder like this:

        body: FutureBuilder(
        future: unpaid(),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM