在 null 上调用了 Flutter 方法
Flutter method was called on null
我正在学习 flutter,我正在尝试实现登录屏幕。我正在关注此 article 并且正在为 API 调用添加 Dio。问题是当我单击“登录”按钮时出现错误 "NoSuchMethod: the method 'authenticate' was called on null"。
这是我所做的。
UserRepository.dart
Future<String> authenticate({
@required String username,
@required String password,
}) async {
await Future.delayed(Duration(seconds: 5));
Map<String, String> body = {
'username': username,
'password': password,
'rememberMe': "false"
};
LoginResponse response = await apiRepository.authenticate(body);
print(response.toString());
return 'token';
}
对于 ApiProvider.dart 我有这个。
class ApiRepository {
final String _baseUrl = "http://myserver/api";
Dio _dio;
ApiProvider() {
BaseOptions options = new BaseOptions(
baseUrl: _baseUrl, receiveTimeout: 5000, connectTimeout: 5000);
_dio = new Dio(options);
}
Future<LoginResponse> authenticate(Map<String, String> body) async {
try {
Response response =
await _dio.post(_baseUrl + "/authenticate", data: body);
print(response.data);
return LoginResponse.fromJson(response.data);
} catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
return LoginResponse.withError(_handleError(error));
}
}
感谢您的帮助。
感谢@Spectarion,我发现了错误。我的错误在于 apiRepository 的实例化。
正确的方法是ApiRepository apiRepository = new ApiRepository();
我的是 ApiRepository apiRepository;
我正在学习 flutter,我正在尝试实现登录屏幕。我正在关注此 article 并且正在为 API 调用添加 Dio。问题是当我单击“登录”按钮时出现错误 "NoSuchMethod: the method 'authenticate' was called on null"。
这是我所做的。
UserRepository.dart
Future<String> authenticate({
@required String username,
@required String password,
}) async {
await Future.delayed(Duration(seconds: 5));
Map<String, String> body = {
'username': username,
'password': password,
'rememberMe': "false"
};
LoginResponse response = await apiRepository.authenticate(body);
print(response.toString());
return 'token';
}
对于 ApiProvider.dart 我有这个。
class ApiRepository {
final String _baseUrl = "http://myserver/api";
Dio _dio;
ApiProvider() {
BaseOptions options = new BaseOptions(
baseUrl: _baseUrl, receiveTimeout: 5000, connectTimeout: 5000);
_dio = new Dio(options);
}
Future<LoginResponse> authenticate(Map<String, String> body) async {
try {
Response response =
await _dio.post(_baseUrl + "/authenticate", data: body);
print(response.data);
return LoginResponse.fromJson(response.data);
} catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
return LoginResponse.withError(_handleError(error));
}
}
感谢您的帮助。
感谢@Spectarion,我发现了错误。我的错误在于 apiRepository 的实例化。
正确的方法是ApiRepository apiRepository = new ApiRepository();
我的是 ApiRepository apiRepository;