我正在调用API从服务器获取数据,并且已经从(https://javiercbk.github.io/json_to_dart/)创建了一个dart文件(模型)
现在我想访问该将来的对象值。
Main.dart
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Row(
children: <Widget>[
RaisedButton(
child: Text("Click"),
onPressed: () async{
setState(() {
apiCall = true; // Set state like this
});
MemberLogin fMain = await getUser();
print('$fMain ');
},
),
],
),
),
);
}
Future<MemberLogin> getUser() async {
try {
final String _endpoint =
"https://api.com/";
Dio dio = new Dio();
Response response = await dio
.post(_endpoint, data: {"new_data": "hello"});
print("user API response - : $response ");
setState(() {
apiCall = false;
});
return MemberLogin.fromJson(response.data);
} catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
//return MemberLogin.withError("$error");
}
}
MemberLogin.dart
class MemberLogin {
int success;
String message;
MemberLogin({this.success, this.message});
MemberLogin.fromJson(Map<String, dynamic> json) {
success = json['success'];
message = json['message'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
data['message'] = this.message;
return data;
}
}
现在,当我在请求message
之后从MemberLogin
打印MemberLogin fMain = await getUser();
时。
我已经调试了代码,可以看到响应,但是无法打印或访问消息字符串。
我该怎么做?
答案 0 :(得分:1)
@deepak,我模拟了一个api,看起来工作正常。您是否尝试以fMain.message
的身份访问邮件?请参见下面的示例,
class MyAppState extends State<MyApp> {
bool apiCall = false;
String message = '';
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(message, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0),),
RaisedButton(
child: Text("Click", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0),),
onPressed: () async{
apiCall = true; // Set state like this
MemberLogin fMain = await getUser();
message = fMain.message;
setState(() {
});
print('$fMain ');
},
),
],
),
),
));
}
Future<MemberLogin> getUser() async {
try {
final String _endpoint =
"http://echo.jsontest.com/key/value/message/testmessage";
Dio dio = new Dio();
Response response = await dio
.get(_endpoint);
print("user API response - : $response ");
setState(() {
apiCall = false;
});
return MemberLogin.fromJson(response.data);
} catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
//return MemberLogin.withError("$error");
}
}
}
class MemberLogin {
String key;
String message;
MemberLogin({this.key, this.message});
MemberLogin.fromJson(Map<String, dynamic> json) {
key = json['key'];
message = json['message'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['key'] = this.key;
data['message'] = this.message;
return data;
}
}