1

我的代码:

  import 'package:http/http.dart' as http;
  import 'dart:convert';
  void main()async {

  var data =await fatchalbum();

   for(int i =0; i>100;i++){
   print(data[i]["userId"]);
   print(data[i]["id"]);
   print(data[i]["title"]);
 }
}

Future fatchalbum()async{
final url ="https://jsonplaceholder.typicode.com/albums";
final res = await http.get(Uri.parse(url));
if(res.statusCode==200){
var obj = json.decode(res.body);
  return obj;
 }else{
 throw Exception("error");
 }
}

如果我在“主函数”中写入 print("hi"); 它可以在调试控制台中运行 "hi"
它不显示其余数据

当我运行代码时,调试控制台中出现此错误

 Failed to save Chrome preferences: FileSystemException: Cannot open file, path = 'C:\Users\dell\AppData\Local\Temp\flutter_tools.ab04b1f8\flutter_tools_chrome_device.49e73a42\Default\Cache\data_0' (OS Error: The process cannot access the file because it is being used by another process.
, errno = 32)

有时当我按下停止然后按下 Run&Debuge 它只显示我,它没有显示我想要的输出:

This app is linked to the debug service: ws://127.0.0.1:55071/6_DbR0EpDJg%3D/ws
Launching lib\main.dart on Edge in debug mode...
lib\main.dart:1
Debug service listening on ws://127.0.0.1:55071/6_DbR0EpDJg=/ws
 Running with sound null safety
Connecting to VM Service at ws://127.0.0.1:55071/6_DbR0EpDJg=/ws
4

3 回答 3

2

这是因为你在for循环中犯了一个错误。它应该i<100不在 for 循环中i>100

...
for(int i =0; i<100;i++){
  print(data[i]["userId"]);
  print(data[i]["id"]);
  print(data[i]["title"]);
 }
...

注意: i<100在 for 循环中,当条件为真时,继续递增直到变为假。

于 2021-10-04T11:11:18.860 回答
2

基本上,您的 fetchalbum 方法返回一个地图列表,因此打印列表的每个元素的最佳方法是使用“For in”循环,这是您应该使用的代码:-

for (var element in data){
print(var["userId"]);
print(var["id"]);
print(var["title"]);
}

您在打印数据的方法中犯了一个小错误,您在循环中给出了当 i 大于 100 i > 100 时,这基本上返回 false,这就是它不打印任何东西的原因。

打印数据的第二种方法是:-

for(int i = o; i <data.length ; i++){
//prints from api
}

或者

for(int i = 0; i <100 ; i++){
//prints from api }
于 2021-10-04T11:25:57.923 回答
1

您应该避免特定长度的条件,尽管它是网络调用并且在您的条件下,当 i 的值大于 100 时您会获取数据。因此,您可以反转您的条件来解决问题。

  for(int i =0; i<data.length;i++){
   print(data[i]["userId"]);
   print(data[i]["id"]);
   print(data[i]["title"]);
 }
于 2021-10-04T11:29:44.733 回答