【发布时间】:2021-10-28 04:45:53
【问题描述】:
好吧,我正在使用 http 的颤振包来处理颤振中的 api 调用。由于我来自js/react/redux 背景,我尝试实施类似的方法。
我创建了一个名为 api 的函数,如下所示,它只是作为包装函数来管理 api 调用,
Future api({
@required String url,
@required String method,
body,
extra,
}) async {
try {
var headers = {
'Content-Type': 'application/json',
"Authorization": ' jwt token of user provider'
};
var request = http.Request(
method, Uri.parse("$SERVER_URL${getUrl(url, method, extra)}"));
if (isSomething(body)) {
request.body = json.encode(body);
}
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
print(response.statusCode);
var responseBody = await response.stream.bytesToString();
print(responseBody);
return responseBody;
} catch (e) {
throw e;
}
但是访问UserProvider 的令牌对我来说似乎很复杂,就像我每次使用它时都必须从我使用api 函数的小部件传递提供程序对象一样。
我的UserProvider 现在看起来像这样:
class UserProvider extends ChangeNotifier {
String id;
String name;
String email;
String role;
String jwt;
void setUser(
{String id, String name, String email, String role, String jwt}) {
print("here is called");
this.id = id;
this.name = name;
this.email = email;
this.role = role;
this.jwt = jwt;
notifyListeners();
}
Map<String, dynamic> getUser() {
return {
"id": this.id,
"name": this.name,
"email": this.email,
"role": this.role,
"jwt": this.jwt
};
}
}
我不知道我是否正确地做这些事情,因为我是 Flutter 的新手。我的问题是:
- 如何在
api函数中访问User provider的jwt? - 这种方法好不好,如果不好,请提出更好的方法。
【问题讨论】: