如何从 JSON 响应中获取特定数据?
How can I reach a specific data from JSON response in flutter?
我正在练习 flutter,我需要使用 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:
class userData {
String deviceId;
String accessToken;
String name;
String surname;
}
userData globaluserData;
这是两个独立的 .dart 文件。所以,在我的回复中,我得到了这些数据,但我怎样才能让它像 -globaluserData.name = response.name-
我做了一些研究,但老实说,我无法理解和适应我的项目的解决方案。
提前致谢!
您可以将您的回复转换为 JSON,然后像访问字典一样访问数据。
if (response.statusCode == 200) {
var jsonResponse = jsonDecode(response.body);
globaluserData.name = jsonResponse['name']
} else {
...
您可以使用 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 阅读更多内容。
我正在练习 flutter,我需要使用 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:
class userData {
String deviceId;
String accessToken;
String name;
String surname;
}
userData globaluserData;
这是两个独立的 .dart 文件。所以,在我的回复中,我得到了这些数据,但我怎样才能让它像 -globaluserData.name = response.name- 我做了一些研究,但老实说,我无法理解和适应我的项目的解决方案。 提前致谢!
您可以将您的回复转换为 JSON,然后像访问字典一样访问数据。
if (response.statusCode == 200) {
var jsonResponse = jsonDecode(response.body);
globaluserData.name = jsonResponse['name']
} else {
...
您可以使用 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 阅读更多内容。