Home > Enterprise >  ListView.builder inside FutureBuilder widget returns null even if it's populated?
ListView.builder inside FutureBuilder widget returns null even if it's populated?

Time:05-28

So I'm new to Flutter and I keep running into the same issue.

Future<List<DonationDTO>> getUsersAppointments() async {
  List<DonationDTO> AppointmentRes = [];
  AppointmentRes = (await _apiClient.getDonationsOfUser(widget.user.id, widget.accesstoken));

return AppointmentRes;
}


@override
Widget build(BuildContext context) {
return SafeArea(
  child: Scaffold(
    appBar: AppBar(
      backgroundColor: Colors.pink,
      elevation: .0,
      leading: BackButton(
          onPressed: () => Navigator.pop(context),
          color: Colors.white),
      title: Text("text"),
    ),
    body:SingleChildScrollView(
      child: FutureBuilder<List<DonationDTO>>(
        future: getUsersAppointments(),
        builder: (context, AsyncSnapshot snapshot) {
          if (!snapshot.hasData || snapshot.hasError) {
            return new Container(child:CircularProgressIndicator());
        } else {
            return Container(
                child: ListView.builder(
                    itemCount: snapshot.data.length,
                    scrollDirection: Axis.horizontal,
                    itemBuilder: (BuildContext context, int index) {
                      if (!snapshot.data[index].hasData || snapshot.data[index].hasError) {
                      return new Container(child:CircularProgressIndicator());
                      } else {
                      return Text('${snapshot.data[index].id}');}
                    }));

         }
        }
      ),
     ),
    ),
   );
  }
 

The problem with this widget is that while using the ListView I keep getting a null value error, more specifically when I try to get data from snapshot.data[index].

It also appears that when I display the content of snapshot.data I get this: [Instance of 'DonationDTO', Instance of 'DonationDTO']

I don't know how to fix this, so any help would be appreciated. Thanks!

CodePudding user response:

snapshot.data[index] points to a list item of DonationDTO type, which has no hasData and hasError properties. In itemBuilder it is safe to use snapshot.data[index] without checks.

CodePudding user response:

Well, the other answer is correct for this case. If you want to solve this not only this time but for all future uses, you should declare your types and not use implicit dynamic that you end up with if you miss a declaration.

A FutureBuilder<List<DonationDTO>> does not receive just any type of AsyncSnapshot. It receives a AsyncSnapshot<List<DonationDTO>>. And from there on, your compiler got your back. .data is no longer of type dynamic where you have to guess (in this specific case you guesses wrong, which explains your problem) but of type List<DonationDTO> and you and your compiler can tell exactly what to do and what would be wrong.

  • Related