0

I have a built an app using flutter that fetches information from an api and it displays it in a list tile. I would like to enable the ontap function so that whenever anyone taps on an item in the list tile it opens another page and displays that information This is the list tile code

 itemCount: prospectList.data.length,
                    itemBuilder: (context, i) {
                      final x = prospectList.data[i];
                      return ListTile(
                        title: Text(x.firstname),
                        subtitle: Text(x.lastname),
                        leading: CircleAvatar(
                          backgroundColor: Colors.green,
                          child: Text(x.firstname[0],
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 20.0,
                              )),
                        ),
                        onTap: () => Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => CustomerInfo())),
                      );

I get this error

The following NoSuchMethodError was thrown building CustomerInfo(dirty, dependencies: [_InheritedTheme, _LocalizationsScope-[GlobalKey#5a50d]]):
The getter 'data' was called on null.
Receiver: null
Tried calling: data

The relevant error-causing widget was
CustomerInfo

The api call

Future<String> _fetchData() async {
    setState(() => loading = true);

    final response = await http.get('run.mocky.io/v3/ad6092cd-3b2d-4b62-92f1-4198f697f3d3');
    if (response.statusCode == 200) {
      final datas = jsonDecode(response.body);
      final prospectListFromJson = ProspectList.fromJson(datas);

      setState(() {
        prospectList = prospectListFromJson;
        loading = false;
      });
    } else {
      print(response.statusCode);
    }
}

  @override
  void initState() {
    super.initState();
    _fetchData();
  }
4

1 回答 1

0

我建议使用FutureBuilder.

Future<ProspectList> _fetchData() async {
  final response = await http.get('run.mocky.io/v3/ad6092cd-3b2d-4b62-92f1-4198f697f3d3');
  if (response.statusCode == 200) {
    var datas;
    datas = jsonDecode(response.body);
    final prospectListFromJson = ProspectList.fromJson(datas);
    return prospectListFromJson;
  } else {
    return null;
  }
}

FutureBuilder(
  future: _fetchData(),
  builder: (BuildContext context, AsyncSnapshot<ProspectList> snapshot){
    if(snapshot.hasData){
      prospectList = snapshot.data;
      if(prospectList != null){
        return List.separated...
      }
      else{
        // Show some error message...
      }
    }
    else if(snapshot.hasError){
      // Show some error message...
    }
    return CircularProgressIndicator();
  }
)

如果您使用 FutureBuilder,您将不必怀疑数据是否已加载。

于 2021-02-26T08:52:32.517 回答