微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我想在颤振中将数据从一个 api 从一个路由发送到另一个路由

如何解决我想在颤振中将数据从一个 api 从一个路由发送到另一个路由

我使用 Flutter 构建了一个应用程序,该应用程序从 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())),);

我收到此错误

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

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

解决方法

我建议使用 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,您就不必怀疑数据是否已加载。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。