首页 > 解决方案 > 在 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));
    }
  }

谢谢你的帮助。

标签: httpdartflutterbloc

解决方案


感谢@Spectarion,我发现了错误。我的错误在于 apiRepository 的实例化。

正确的方法是ApiRepository apiRepository = new ApiRepository();

我的是ApiRepository apiRepository;


推荐阅读