Flutter FutureBuilder返回空数据

时间:2019-11-12 22:41:13

标签: api flutter dart future statefulwidget

我是Flutter和Dart的新手,我正在尝试编写一个应用程序对其进行测试。 我有一个API,我正在获取应用程序的数据,并试图使用StatefulWidget和FutureBuilder。

当我运行该方法以调用api时,我得到了结果(使用print()对其进行了测试),但是当我从loadData方法获取数据时,它会检索null。

因此loadData打印数据,initState和FutureBuilder数据返回null。我在这里想念什么。

我已经添加了服务和用于请求的模型...希望对您有所帮助。

Future<CoachesModelRes> loadData(Profile _profile) async {
await getPost(_profile.getToken()).then((response) {
  if (response.statusCode == 200) {
    CoachesModelRes coaches = coachesModel.postFromJson(response.body);

    if (coaches.count > 0) {
      print(coaches.count);
      print(coaches.coaches[0].description);
      return coaches;
    } else {
      return null;
    }
  } else {
    String code = response.statusCode.toString();
    return null;
  }
}).catchError((error) {
  print(error.toString());
  return null;
});
}

@override
void initState() {
  super.initState();
  print(widget.profile.getToken());
  data = loadData(widget.profile);
  data.then((data_) async {
    var cenas = data_.count;
    print("asdasd $cenas");
  });
}

Future<CoachesModelRes> data;

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: appWhiteColor,
  appBar: applicationBar(),
  drawer: adminDrawer(widget.profile, AdminDrawerListEnum.coaches, context),
  body: FutureBuilder<CoachesModelRes>(
    future: data,
    builder: (context, snapshot) {
      //print(snapshot.data.count.toString());
      if (snapshot.hasData) {
        return Text("nop");
      } else if (snapshot.hasError) {
        return Text("${snapshot.error}");
      }
      return Text("nop");
      // By default, show a loading spinner.
      return CircularProgressIndicator();
    },
  ),
);
}

Future<http.Response> getPost(String token) async {
   final response = await http.get(new Uri.http("$apiUrl", "$coachesEndPoint"),
     headers: {
      HttpHeaders.contentTypeHeader: 'application/json',
      HttpHeaders.authorizationHeader : 'Bearer $token'
     },
  );
  return response;
}


CoachesModelRes postFromJson(String str) => CoachesModelRes.fromJson(json.decode(str));

class CoachesModelRes {

 int count;
 List<CoachModelRes> coaches;

 CoachesModelRes({
    this.count,
    this.coaches,
 });

 factory CoachesModelRes.fromJson(Map<String, dynamic> json) => new CoachesModelRes(
    count: json["count"],

    coaches: (json["coaches"] as List).map((i) => CoachModelRes.fromJson(i)).toList(),
 );
}


CoachModelRes postFromJson(String str) => CoachModelRes.fromJson(json.decode(str));

class CoachModelRes {

    String id;
    String firstName;
    String lastName;
    String description;
    String username;
    String notes;
    List<String> roles;

    CoachModelRes({
        this.id,
        this.firstName,
        this.lastName,
        this.description,
        this.username,
        this.notes,
        this.roles,
    });

    factory CoachModelRes.fromJson(Map<String, dynamic> json) => new CoachModelRes(
        id: json["id"],
        firstName: json["firstName"],
        lastName: json["lastName"],
        description: json["description"],
        username: json["username"],
        notes: json["notes"],
        roles: new List<String>.from(json["roles"]),
    );
}

2 个答案:

答案 0 :(得分:0)

public Dictionary<string, int> SensorValues => InOrderSensorValues
      .Select(sv => sv.Split(':'))
      .GroupBy(svp => svp[0].ToUpper(), svp => svp[1])
      .ToDictionary(
         kvp => kvp.Key, 
         kvp => int.Parse(kvp.First()));

答案 1 :(得分:0)

这里的问题是return语句应该在方法的末尾。

因为getPost会将数据返回到loadData

getPost完成后,loadData会将数据返回给调用他的方法。

在我的情况下,loadData没有返回任何内容,因此snapshot中的FutureBuilder始终为空。

现在是这种逻辑是合理的,但是当时我无法弄清楚:\

Future<CoachesModelRes> loadData(Profile _profile) async {
// So I need to create a variable to return
CoachesModelRes response;
//-----
await getPost(_profile.getToken()).then((response) {
  if (response.statusCode == 200) {
    CoachesModelRes coaches = coachesModel.postFromJson(response.body);

       if (coaches.count > 0) {
         print(coaches.count);
         print(coaches.coaches[0].description);
         // Set the variable value
         response = coaches;
         //-----
       } else {
         // Set the variable value
         response = null;
         //-----
       }
     } else {
       String code = response.statusCode.toString();
       // Set the variable value
       response = null;
       //-----
     }
   }).catchError((error) {
     print(error.toString());
     // Set the variable value
     response = null;
     //-----
   });
   // And at the end return the response variable
   return response;
   //-----
}