http - 在 null 上调用了 Flutter 方法
问题描述
我正在学习颤振,我正在尝试实现登录屏幕。我正在关注这篇文章,我正在为 API 调用添加 Dio。问题是当我单击登录按钮时,我收到错误“NoSuchMethod:方法'authenticate'被调用为null”。
这是我所做的。
用户存储库.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;
推荐阅读
- java - Android:我请求权限的问题。里面的代码
- regex - 如何正确匹配只需要的数字类型
- python - 使用 python 从 Outlook 解析 Ics 文件
- python - 在重复的情况下仅对列表的一个值求和并将其转换为字典
- variables - jupyter_contrib_nbextensions 变量检查器不存储/显示变量?
- random - 偏差如何在有界随机数生成中表现出来
- react-native - 如何让 KeyboardAvoidingView 与 Formik 向导一起工作?
- python - 熊猫数据透视表不添加但连接值
- c - 在 C (linux) 中使用 opendir 读取两个目录
- python - 为什么我在 python 中的循环函数返回错误的值?