0

我在我的代码中采用了 Dart 启用的新 Null Safety 功能。目前,我面临以下问题:

在 SearchDelegate 类中,我从重写的方法“buildSuggestions”中调用工厂方法 getLocations:

@override
 Widget buildSuggestions(BuildContext context) {

   if (query.isNotEmpty && query.length > 10) {

     final Future<ApiLocation> locationsSuggested = getIt.getAsync<ApiLocation>(param1: query);

正如我在前面的代码中指出的那样,我将自定义参数传递给 factoryParamAsync,目的是将搜索字符串传递给 googleplaces api:

@injectable
class ApiLocation {

  final Map<String,dynamic> _listLocations;
  
  ApiLocation(
      this._listLocations,
      );

  Map<String,dynamic> get listLocations {
    return _listLocations;
  }

  @factoryMethod
  static Future<ApiLocation> getLocations(@factoryParam String? searchString) async {

    final url = Uri.https('maps.googleapis.com','/maps/api/place/autocomplete/json', {
      'input': searchString,
      'key': '...',
      'language': 'es',
      'types': 'address',
      'sessiontoken': '...',
    });

    final response = await http.get(url,
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
    );

    final Map<String,dynamic> respuesta={
      'code': response.statusCode.toString(),
      'message': json.decode(response.body),
    };

    return ApiLocation(respuesta);
  }

}

新的 Null Safety 功能强制将 factoryParam 声明为可为空。

这里的要点是所有代码以前都像一个魅力一样工作,但是一旦采用新功能,就会抛出以下错误:

Error while creating ApiLocation
I/flutter (10807): Stack trace:
I/flutter (10807):  #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
I/flutter (10807): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
I/flutter (10807): #2      _ServiceFactory.getObjectAsync (package:get_it/get_it_impl.dart:167:17)
I/flutter (10807): #3      _GetItImplementation.getAsync (package:get_it/get_it_impl.dart:384:25)
I/flutter (10807): #4      LocationSearch.buildSuggestions (package:karabitner_mobile/presentation/new_card_page/new_card_page.dart:2669:60)
I/flutter (10807): #5      _SearchPageState.build (package:flutter/src/material/search.dart:532:34)
I/flutter (10807): #6      StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
I/flutter (10807): #7      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
I/flutter (10807): #8      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4667:11)
I/flutter (10807): #9      Element.rebuild (package:flutter/src/widgets/framework.dart:4189:5)
I/flutter (10807): #10     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2694:33)
I/flutter (10807): #11     WidgetsBinding.drawFrame (package:flutter/src/widgets/bindi

我试图将变量字符串“查询”转换为字符串?并对其进行测试,得到相同的错误。我尝试使用 factoryAsync 中的“instanceName”参数,尽管我在一些响应中看到它是不推荐的。

我希望我对这个问题有一个清晰的认识,任何建议都会受到欢迎。

4

0 回答 0