我如何从 class extends ChangeNotifier 中获取价值
How I can get value from class extends ChangeNotifier
[我的代码] .当我使用 User user = Provider.of(context, listen: false).user; => 用户空
My code here
class UserController extends ChangeNotifier {
User _user;
User get user => _user;
Future<void> getUser() async {
String token = await AppValue.getToken();
Uri uri = Uri.parse('http://20.89.111.129/api/user/getProfileUser');
Map<String, String> headers = {'Authorization': 'Bearer $token'};
try {
final response = await http.get(
uri,
headers: headers,
);
final data = jsonDecode(response.body);
User newUser = new User(
address: (data['address'] == null) ? '' : data['address'],
birthday: (data['birthday'] == null) ? '' : data['birthday'],
email: (data['email'] == null) ? '' : data['email'],
fullName: (data['fullName'] == null) ? '' : data['fullName'],
);
_user = newUser; // _user is not null
notifyListeners();
} catch (error) {
log('ST WRONG!');
throw (error);
}
}
}
// 当我使用 User 时 user = Provider.of(context, listen: false).user; => 用户空
我认为你需要告诉提供者你想要采取行动的确切 class,
//so instead of this;
User user = Provider.of(context, listen: false).user;
// do this
User user = Provider.of< UserController>(context, listen: false).user;
[我的代码] .当我使用 User user = Provider.of(context, listen: false).user; => 用户空 My code here
class UserController extends ChangeNotifier {
User _user;
User get user => _user;
Future<void> getUser() async {
String token = await AppValue.getToken();
Uri uri = Uri.parse('http://20.89.111.129/api/user/getProfileUser');
Map<String, String> headers = {'Authorization': 'Bearer $token'};
try {
final response = await http.get(
uri,
headers: headers,
);
final data = jsonDecode(response.body);
User newUser = new User(
address: (data['address'] == null) ? '' : data['address'],
birthday: (data['birthday'] == null) ? '' : data['birthday'],
email: (data['email'] == null) ? '' : data['email'],
fullName: (data['fullName'] == null) ? '' : data['fullName'],
);
_user = newUser; // _user is not null
notifyListeners();
} catch (error) {
log('ST WRONG!');
throw (error);
}
}
}
// 当我使用 User 时 user = Provider.of(context, listen: false).user; => 用户空
我认为你需要告诉提供者你想要采取行动的确切 class,
//so instead of this;
User user = Provider.of(context, listen: false).user;
// do this
User user = Provider.of< UserController>(context, listen: false).user;