繁体   English   中英

无法从 api 获取数据,Future 总是返回 null - flutter

[英]Cannot fetch data from api, Future always returns null - flutter

我正在尝试从 flutter 中的 API 获取数据。 Just to test I was using the API URL: https://jsonplaceholder.typicode.com/todos/1 which has the following JSON object:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

我在网上按照一个示例进行了几乎完全调整以匹配我想要的工作流程,但下面的snapshot.hasData返回 false。

class Home extends StatelessWidget {
  final String accountNum;
  Home(this.accountNum);
  final String apiUrl = "https://jsonplaceholder.typicode.com/todos/";

  Future<Map<String, dynamic>> fetchData() async {
    //accountNum below is passed from a previous screen, in this case I pass '1'
    //I printed it to make sure that '1' is passed and it is correct
    var result = await http.get(apiUrl+accountNum);
    //I printed the below and it also gave me the json from the api
    //print(json.decode(result.body));
    return json.decode(result.body);
  }

  String _MeterNum(dynamic account){
    return account['title'];
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Account Data'),
      ),
      body: Container(
        child: FutureBuilder<Map<String, dynamic>>(
          future: fetchData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if(snapshot.hasData){
              print(_MeterNum(snapshot.data[0]));
              return ListView.builder(
                  padding: EdgeInsets.all(8),
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index){
                    return
                      Card(
                        child: Column(
                          children: <Widget>[
                            ListTile(
                              leading: CircleAvatar(
                                  radius: 30,
                                  backgroundImage: NetworkImage(snapshot.data[index]['picture']['large'])),
                              //I realize this will just show the same thing 
                              //but I was just keeping the format of the example I was following
                              title: Text(_MeterNum(snapshot.data[index])),
                              subtitle: Text(_MeterNum(snapshot.data[index])),
                              trailing: Text(_MeterNum(snapshot.data[index])),
                            )
                          ],
                        ),
                      );
                  });
            }else {
              return Center(child: CircularProgressIndicator());
            }
          },


        ),
      ),
    );
  }
}

返回的是CircularProgressIndicator()到模拟器屏幕,表明snapshot.hasData为假。 我在控制台或任何东西中都没有收到任何错误,所以我不确定如何继续。

---编辑---使用评论者的建议对上面的代码进行了更改:

将返回类型从 Future<List> 更改为 Future<Map<String, dynamic>> 并更改了 'return json.decode(result.body)['results'];' '返回 json.decode(result.body)'

现在我收到以下错误:

在构建 FutureBuilder<Map<String, dynamic>>(dirty, state: _FutureBuilderState<Map<String, dynamic>>#a10d4) 时引发了以下 NoSuchMethodError:

在 null 上调用了方法“[]”。 接收器:null

尝试调用:[](“标题”)

在检查hasData之前,请执行以下操作:

if (snapshot.connectionState == ConnectionState.done) {
              // your code
}

编辑

你的申请

var result = await http.get(apiUrl+accountNum);

返回 JSON object 而不是 JSON 列表。 但是在您将其更新为 Future<Map<String, dynamic>> 之前,您的fetchData方法的返回类型是 List。 像这样写你的方法

Future<Map<String, dynamic>> fetchData() async {
    var result = await http.get(apiUrl+accountNum);
    return json.decode(result.body);
}

不需要 json.decode(result.body)['results'],因为您只获取 object 而不是列表。

改变

title: Text(_MeterNum(snapshot.data[index])),
subtitle: Text(_MeterNum(snapshot.data[index])),
trailing: Text(_MeterNum(snapshot.data[index])),

title: Text(_MeterNum(snapshot.data)),
subtitle: Text(_MeterNum(snapshot.data)),
trailing: Text(_MeterNum(snapshot.data)),

没有键为['picture']['large']所以注释掉ListTile中的那个键

API 响应是 JSON object

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

并且仅包含userIdidtitlecompleted的成员

而不是参考索引,请考虑从 object 获取。

代替

snapshot.data[index]

 snapshot.data

snapshot.data['picture']['large']

您在 JSON object 中没有picture数据,请尝试评论该代码或添加图片

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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