Flutter:HTTP Get 在 null 上调用了 getter 'length'

时间:2021-01-23 16:41:31

标签: flutter

我的 http get 函数无法从 laravel 后端接收响应。它只是继续说明在 null 上调用了 getter 'length'。当我在浏览器或邮递员上测试 api http://localhost/ioio/public/api/settings 时,它能够接收数据和响应,所以我不确定为什么在颤振中我无法接收响应。

这是我的存储库功能。我试图打印出来看看代码在哪里出错。它停在 final response =... 行,然后会导致 catch 函数出错。我也试过使用 await http.get('http://localhost/ioio/public/api/settings'); 但结果是一样的。

Future<Setting> initSettings() async {
  Setting _setting;
  final String url = '${GlobalConfiguration().getString('api_base_url')}settings';
  try {
    final response = await http.get(url, headers: {HttpHeaders.contentTypeHeader: 'application/json'});
    if (response?.statusCode == 200 && response.headers.containsValue('application/json')) {
      if (json.decode(response.body)['data'] != null) {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        await prefs.setString('settings', json.encode(json.decode(response.body)['data']));
        _setting = Setting.fromJSON(json.decode(response.body)['data']);
        if (prefs.containsKey('language')) {
          _setting.mobileLanguage.value = Locale(prefs.get('language'), '');
        }
        _setting.brightness.value = prefs.getBool('isDark') ?? false ? Brightness.dark : Brightness.light;
        setting.value = _setting;
        // ignore: invalid_use_of_visible_for_testing_member, invalid_use_of_protected_member
        setting.notifyListeners();
      }
    } else {
      print(CustomTrace(StackTrace.current, message: response.body).toString());
    }
  } catch (e) {
    print(CustomTrace(StackTrace.current, message: url).toString());
    return Setting.fromJSON({});
  }
  return setting.value;
}

这是打印出捕获错误的消息。

Error in (initSettings (package:ioio/src/repository/settings_repository.dart:52:34)) | [http://localhost/ioio/public/api/settings] 
I/flutter (10877): NoSuchMethodError: The getter 'length' was called on null.
I/flutter (10877): Receiver: null
I/flutter (10877): Tried calling: length

这是我的主类在初始化期间调用 initSettings 函数的地方。

@override
  void initState() {
    settingRepo.initSettings(); //this line
    settingRepo.getCurrentLocation();
    userRepo.getCurrentUser();
    super.initState();
  }

这是第 52 行

print(CustomTrace(StackTrace.current, message: url).toString());

这是发生异常的行

final response = await http.get(url, headers: {HttpHeaders.contentTypeHeader: 'application/json'});

0 个答案:

没有答案