【问题标题】:Does not appear the output in Debug console不会在调试控制台中出现输出
【发布时间】:2021-11-24 19:38:14
【问题描述】:

我的代码:

  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

【问题讨论】:

  • “它没有向我显示我想要的输出” - 一句话概括了我的编码生涯。
  • for 循环条件为假..

标签: flutter dart visual-studio-code


【解决方案1】:

基本上,您的 fetchalbum 方法返回一个地图列表,因此打印 List 的每个元素的最佳方法是使用“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 }

【讨论】:

  • 使用“for in loop”时,不显示数据
  • 首先检查你得到的数据的数据类型,如果它的映射而不是用键打印它
【解决方案2】:

这是因为您在for 循环中犯了一个错误。它应该是 for 循环中的 i&lt;100 而不是 i&gt;100。

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

注意: for 循环中的i&lt;100 表示,当条件为真时,继续递增直到变为假。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-18
      • 2012-08-07
      • 1970-01-01
      相关资源
      最近更新 更多