【问题标题】:how handle message from API - flutter如何处理来自 API 的消息 - 颤振
【发布时间】: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 != nulldata的值是多少?
  • 我加了一个答案,你试过这样吗?

标签: api flutter dart


【解决方案1】:

由于您已经在 Future 中正确返回数据,您只需使用它来显示 SnackBar。

if (data != null) {
  Navigator.pop(context);

  // Add this line
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(data)));
}

【讨论】:

  • 但我还有其他问题。从 api 获取数据后,我想留在同一个屏幕上。 .我认为这是关于 setState(() {} 的问题。我该如何解决?
  • 删除Navigator.pop(context); 行。它的作用是删除当前页面,以便您返回上一页
  • 你是个好人。它工作正常。我还有其他小问题。从 api 获取数据后...输入文本仍然有效。我希望在获取数据后禁用输入文本。
  • 是的,你可以在我给你的新Snackbar代码上方添加setState(() { enableadress = false; })
  • 在单个setState内,逐行添加所有代码
猜你喜欢
  • 2022-06-16
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多