Dart 编译器将泛型作为对象

Dart compiler gets generic as object

我目前正在构建一个 dart/flutter 应用程序,我正在尝试使用泛型。有一个 Api-Call,其中 returns class 结果包含错误或获取的 json。我在结果 class 中创建了一个函数,用于处理错误和实际结果。一个选项是指定一个函数来解析 json(否则指定一个空结果作为函数)。此函数 returns 类型参数 T。如果不存在错误、指定的有效解析函数和存在的结果将调用此解析函数并将其传递给 onSuccess 函数。

现在的问题: dart/flutter 编译器不再识别类型参数,而是将其识别为对象...我不知道为什么...

这里是必要的代码:

句柄函数:

  static final expectEmpty = Result.empty();

  Widget handle<T>(
      T Function(Map<String, dynamic>) parse,
      Widget? Function(ApiError)? onError,
      Widget Function(T) onSuccess
      ) {
    Widget? ret;
    if (errorPresent()) {//If error occurred
      if (onError != null) ret = onError(error!);//Error which could be thrown
      return ret ?? handleCommonError();//If error wasn't handled
    } else {
      if (resultPresent() && T is! Result) {//If result present and valid parse function specified
        return onSuccess(parse(result!));//Return Widget function onSuccess with parsed result
      } else if (T is Result) {//Otherwise if empty result is expected
        return onSuccess(expectEmpty as T);//Return onSuccess without parse
      } else {//If nothing handled, try common errors
        return handleCommonError();
      }
    }
  }

句柄函数的调用:

     if (snapshot.hasData) {
          return snapshot.data!.handle((json) => Articles.fromJson(json).articles,
                  (error) {
                    //TODO: implement errors
                  },
                  (articles) {
                    return ListView.separated(
                        itemBuilder: (context, index) {
                          final article = articles![index];
                          return _newsCard(article);
                        },
                        separatorBuilder: (context, index) {
                          return const Divider(height: 0);
                        },
                        itemCount: articles!.length);
                  });
        }

编译器输出:

解决了我的问题: 如果调用 handle(... 编译器没有任何线索,因为在指定的函数调用上没有通用类型。为避免必须在函数调用中指定它: handle<Articles>(...

来源:

https://github.com/flutter/flutter/issues/89745

https://github.com/dart-lang/sdk/issues/42766