我如何从类扩展ChangeNotifier中获取价值

问题描述 投票:0回答:1

如何从类扩展 ChangeNotifier 中获取价值 当我使用

User user = Provider.of<UserController>(context, listen: false).user; => user null

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);
}
}
}
// When I use User user = Provider.of<UserController>(context, listen: false).user; => user null
flutter future flutter-provider
1个回答
1
投票

我认为您需要告诉提供者您想要执行的确切类别,

//so instead of this;
User user = Provider.of(context, listen: false).user;

// do this
User user = Provider.of< UserController>(context, listen: false).user;

© www.soinside.com 2019 - 2024. All rights reserved.