【发布时间】:2021-08-12 20:32:45
【问题描述】:
我是 Flutter 的新手。我正在处理 API 请求。来自服务器的我的 API 响应如下:
{
"code": 1,
"message": "User name updated with success !",
"data": [],
"error": [],
"status": 200
}
我想在snackbar中向用户显示消息内容。
我的代码:
Future<String> editUserProfile(
String name, String email, String adress) async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
String token = localStorage.getString('access_token');
await checkInternet();
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
Map<String, dynamic> body = {
'name': name,
'email': email,
'adress': adress,
};
var response = await http.post(Uri.parse(ApiUtil.MODIFY_USER_PROFILE),
headers: headers, body: jsonEncode(body));
print(response.statusCode);
print(response);
inspect(response);
if (response.statusCode == 200) {
if (response.body.isNotEmpty) {
body = jsonDecode(response.body);
}
var data = body['message'];
return data;
} else {
throw Exception('Failed to modify name');
}
}
void editUserProfile() async {
setState(() {});
String name = _nameController.text;
String email = _emailController.text;
String adress = _adressController.text;
userApi.editUserProfile(name, email, adress).then((data) {
if (data != null) {
Navigator.pop(context);
}
}).catchError((error) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(error.toString())));
});
setState(() {});
}
如何在snackBar 中动态显示从后端获取的消息给用户?
更多信息:
更新1:输入文本代码:
Row(
mainAxisAlignment:MainAxisAlignment.spaceBetween,
children: [
Text(
'Adresse :',
style: TextStyle(
color: Color( 0xFF4053FCF),
fontSize: 16,
fontWeight:FontWeight.w600),
),
IconButton(
icon: Icon(CommunityMaterialIcons.pencil,
color: Colors.grey,
),
onPressed: () {
adresseNode.requestFocus();
setState(() {
enableadress = true;
});
})
],
),
TextFormField(
enabled: enableadress,
controller:_adressController,
focusNode: adresseNode,
enableInteractiveSelection: false,
keyboardType: TextInputType.text,
decoration: InputDecoration(
hintText: "${snapshot.data.adress}",
hintStyle: TextStyle(color: Colors.grey,fontSize:14.0)),
),
【问题讨论】:
-
您似乎已准备就绪。似乎是什么问题
-
在我的情况下,我无法收到消息:用户名已成功更新!
-
出现在控制台但没有出现在屏幕上
-
检查
data != null时data的值是多少? -
我加了一个答案,你试过这样吗?