0

我是 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"]),
    );
}
4

2 回答 2

0
 Future<CoachesModelRes> loadData(Profile _profile) async {
     final response = await  getPost(_profile.getToken());
    try{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;
  }}catch(e){

    return null ; 
  }
   } 
@override
void initState() {
  super.initState();

}

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: appWhiteColor,
  appBar: applicationBar(),
  drawer: adminDrawer(widget.profile, AdminDrawerListEnum.coaches, context),
  body: FutureBuilder<CoachesModelRes>(
    future: loadData(widget.profile),
    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();
    },
  ),
);
}
于 2019-11-12T22:51:26.780 回答
0

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

因为getPost会将数据返回给loadData.

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

在我的情况下,loadData它没有返回任何东西,所以snapshotFutureBuilder总是为空。

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

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;
   //-----
}
于 2020-02-26T22:26:27.127 回答