【问题标题】:Dart compiler gets generic as objectDart 编译器作为对象获得泛型
【发布时间】:2021-09-08 20:20:15
【问题描述】:

我目前正在构建一个 dart/flutter 应用程序,并且正在尝试使用泛型。有一个 Api-Call 返回包含错误的类 Result 或获取的 json。我在结果类中创建了一个函数,用于处理错误和实际结果。一个选项是指定一个函数来解析 json(否则指定一个空结果作为函数)。此函数返回类型参数 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);
                  });
        }

编译器输出:

【问题讨论】:

    标签: flutter dart generics compiler-errors functional-programming


    【解决方案1】:

    我的问题: 如果handle(... 被调用,编译器没有任何线索,因为在指定的函数调用上没有泛型类型。为避免这种情况,必须在函数调用中指定: handle&lt;Articles&gt;(...

    来源:

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

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

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 2021-12-18
    • 2022-11-12
    • 2011-07-17
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多