Я хочу отправлять данные из api с одного маршрута на другой во флаттере

У меня есть приложение, использующее флаттер, которое извлекает информацию из API и отображает ее в виде плитки со списком. Я хотел бы включить функцию ontap, чтобы всякий раз, когда кто-либо нажимал на элемент в плитке списка, он открывал другую страницу и отображал эту информацию. Это код плитки списка

       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())),
                      );

Это код для CustomerInfo, в котором я хотел бы его отобразить.

        ProspectList prospectList;
  @override
  Widget build(BuildContext context) {
    var i;
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          "Details"),
      body: SingleChildScrollView(
        child: Padding(
          child: Card(
            child: Column(
              children: <Widget>[
                ListTile(
                    title: Text('Firstname'),
                    subtitle: Text(
                      prospectList.data[i].firstname,
                    )),
                ListTile(
                    title: Text('Last Name'),
                    subtitle: Text(
                      prospectList.data[i].firstname,
                    )),
                ListTile(
                    title: Text('Phone Number'),
                    subtitle: Text(
                      prospectList.data[i].firstname,
                    )),
                ListTile(
                    title: Text('Speculated Amount'),
                    subtitle: Text('${prospectList.data[i].amountSpeculated}')),
              ],
            ),
          ),
        ),
      ),
    );
  }

Я получаю эту ошибку

      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

Код ProspectList https://github.com/Kevnlan/flutter-list/blob/main/model/

Вызов API

      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();
  }

1 ответ

Я бы предложил использовать 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, вам не придется задаваться вопросом, были ли данные загружены или нет.

Другие вопросы по тегам