【问题标题】:How can I reach a specific data from JSON response in flutter?如何在颤动中从 JSON 响应中获取特定数据?
【发布时间】:2021-03-10 01:17:37
【问题描述】:

我正在练习颤振,我需要使用 JSON 格式的响应数据。这是我的 POST 请求:

    final response = await http.post(url,
        headers: {"Content-type": "application/json", "accept": "/"},
        body: json.encode({
          'username': id,
          'password': pwd,
          'deviceId': devid,
        }));
    if (response.statusCode == 200) {
      check = true;
      print("OK");
    } else {
      check = false;
      print("NOT OK");
    }
    print(response.body);
  }

还有我的用户数据类:

class userData {
  String deviceId;
  String accessToken;
  String name;
  String surname;
}
userData globaluserData;

这是两个单独的 .dart 文件。所以,在我的回复中,我得到了这些数据,但我怎样才能让它像 -globaluserData.name = response.name- 我做了一些研究,但老实说,我无法理解和适应我的项目的解决方案。 提前致谢!

【问题讨论】:

    标签: json flutter dart httpresponse


    【解决方案1】:

    您可以将响应转换为 JSON,然后像字典一样访问数据。

    if (response.statusCode == 200) {
      var jsonResponse = jsonDecode(response.body);
    
      globaluserData.name = jsonResponse['name']
    } else {
    ...
    

    【讨论】:

      【解决方案2】:

      您可以使用app state provider 访问整个项目中的变量。您的提供者将如下所示:

      import 'package:flutter/material.dart';
      
      class AppStateProvider extends ChangeNotifier {
        UserData _currentUser;
      
        void setCurrentUser(UserData currentUser) {
          _currentUser = currentUser;
      
          //Call this whenever there is some change in any field of change notifier.
          notifyListeners();
        }
      
      
        //Getter for current user 
        UserData get currentUser => _currentUser;
      }
      
      

      您可以从here阅读更多内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 2015-04-15
        • 2021-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多