问题描述
我正在使用Rest API调用GET方法来获取一些数据。我正在执行此操作以加载配置文件以查看我的拍打物体内部。我试图将这些数据分配给FutureBuilder方法中的String变量。 在将来的构建器中,应该返回fetchUser()API调用响应,但是快照返回null。因此,每当我尝试运行此命令时,屏幕就会停留在CircularProgressIndicator中。 有人可以帮我弄清楚我在哪里做错了以及如何解决吗?
扑页中的正文
final userProfileView = FutureBuilder<UserFetch>(
future: CallApi().fetchUser(apiUrl),builder: (context,snapshot) {
if(!snapshot.hasData)//(!snapshot.hasData)
return Center(
widthFactor: 120.0,heightFactor: 120.0,child: CircularProgressIndicator(),);
// final userD = snapshot.data;
_userName = snapshot.data.user.username.toString();
_userEmail = snapshot.data.user.email;
_userAddress = snapshot.data.user.address.toString();
_userPassword = 'password';
_userCountry = 'country';
_userMobile = snapshot.data.user.mobile.toString();
//checks if the response returns valid data
return Container(
child: Padding(
padding:
const EdgeInsets.symmetric(vertical: 8.0,horizontal: 16.0),child: SingleChildScrollView(
child: Column(
children: <Widget>[
userTitle,SizedBox(height: 12.0),userNameTitle,userName,userEmailTitle,userEmail,userPasswordTitle,userPassword,userAddresstitle,userAddress,userCountryTitle,userCountry,userPhoneTitle,userPhone,SizedBox(height: 24.0),userlogoutBtn,],),);
// } else if (snapshot.hasError) {
// //checks if the response throws an error
// return Text("${snapshot.error}");
// }
});
Api电话
Future<UserFetch> fetchUser(apiUrl) async {
var fullUrl = _baseUrl + apiUrl;
final response = await http.get(fullUrl,headers: _setHeaders());
if (response.statusCode == 200) {
// If the call to the server was successful (returns OK),parse the JSON.
return UserFetch.fromJson(json.decode(response.body));
} else {
// If that call was not successful (response was unexpected),it throw an error.
throw Exception('Failed to load User');
}
}
响应模型
UserFetch userFetchFromJson(String str) => UserFetch.fromJson(json.decode(str));
String userFetchToJson(UserFetch data) => json.encode(data.toJson());
class UserFetch {
UserFetch({
this.success,this.user,});
bool success;
User user;
factory UserFetch.fromJson(Map<String,dynamic> json) => UserFetch(
success: json["success"],user: User.fromJson(json["user"]),);
Map<String,dynamic> toJson() => {
"success": success,"user": user.toJson(),};
}
class User {
User({
this.email,this.address,this.imperial,this.mobile,this.petsInfo,this.role,this.subscribed,this.username,});
String email;
String address;
bool imperial;
String mobile;
List<PetsInfo> petsInfo;
String role;
bool subscribed;
String username;
factory User.fromJson(Map<String,dynamic> json) => User(
email: json["email"],address: json["address"],imperial: json["imperial"],mobile: json["mobile"],petsInfo: List<PetsInfo>.from(json["pets_info"].map((x) => PetsInfo.fromJson(x))),role: json["role"],subscribed: json["subscribed"],username: json["username"],dynamic> toJson() => {
"email": email,"address": address,"imperial": imperial,"mobile": mobile,"pets_info": List<dynamic>.from(petsInfo.map((x) => x.toJson())),"role": role,"subscribed": subscribed,"username": username,};
}
class PetsInfo {
PetsInfo({
this.id,this.name,});
int id;
String name;
factory PetsInfo.fromJson(Map<String,dynamic> json) => PetsInfo(
id: json["id"],name: json["name"],dynamic> toJson() => {
"id": id,"name": name,};
}
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
'package:Flutter/src/widgets/framework.dart': Failed assertion: line 273 pos 18: '_registry.containsKey(key)': is not true.
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown while finalizing the widget tree:
'package:Flutter/src/widgets/framework.dart': Failed assertion: line 273 pos 18: '_registry.containsKey(key)': is not true.
Either the assertion indicates an error in the framework itself,or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case,please report this assertion by filing a bug on GitHub:
https://github.com/Flutter/Flutter/issues/new?template=BUG.md
When the exception was thrown,this was the stack:
#2 GlobalKey._debugVerifyIllFatedPopulation.<anonymous closure> (package:Flutter/src/widgets/framework.dart:273:18)
#3 GlobalKey._debugVerifyIllFatedPopulation (package:Flutter/src/widgets/framework.dart:298:6)
#4 BuildOwner.finalizeTree.<anonymous closure> (package:Flutter/src/widgets/framework.dart:2769:21)
#5 BuildOwner.finalizeTree (package:Flutter/src/widgets/framework.dart:2849:8)
#6 WidgetsBinding.drawFrame (package:Flutter/src/widgets/binding.dart:915:18)
解决方法
将未来类型用于API调用函数,因为无法确定像这样将来会发生什么
Future<dymamic> fetchUser(apiUrl) async {
var fullUrl = _baseUrl + apiUrl;
final response = await http.get(fullUrl,headers: _setHeaders());
if (response.statusCode == 200) {
// If the call to the server was successful (returns OK),parse the JSON.
return UserFetch.fromJson(json.decode(response.body));
} else {
// If that call was not successful (response was unexpected),it throw an error.
throw Exception('Failed to load User');
}
}
现在检查FutureBuiler
中的响应是否引发错误。
if(snapshot.data=="Failed to load User"){
return Text("something went wrong");
}