首页 > 解决方案 > Dart - 类型冲突

问题描述

我目前正在使用一个 proto 文件,该文件定义了系统使用的多种类型。

使用 protoc 将其编译为 dart 可以正常工作,但是尝试在项目中使用它会导致问题

proto 中定义的消息之一是String它有一个string值,这似乎与 Darts 核心String类型冲突,我在下面放了一段生成的代码:

import 'dart:core' show int, bool, double, String, List, Map, override;
import 'package:fixnum/fixnum.dart';
import 'package:protobuf/protobuf.dart' as $pb;
import 'Framework.pbenum.dart';
export 'Framework.pbenum.dart';

class String extends $pb.GeneratedMessage {
  static final $pb.BuilderInfo _i = new $pb.BuilderInfo('String', package: const $pb.PackageName('sila2.org.silastandard'))
    ..aOS(1, 'value')
    ..hasRequiredFields = false
  ;

  String() : super();
  String.fromBuffer(List<int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) : super.fromBuffer(i, r);
  String.fromJson(String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) : super.fromJson(i, r);
  String clone() => new String()..mergeFromMessage(this);
  String copyWith(void Function(String) updates) => super.copyWith((message) => updates(message as String));
  $pb.BuilderInfo get info_ => _i;
  static String create() => new String();
  String createEmptyInstance() => create();
  static $pb.PbList<String> createRepeated() => new $pb.PbList<String>();
  static String getDefault() => _defaultInstance ??= create()..freeze();
  static String _defaultInstance;
  static void $checkItem(String v) {
    if (v is! String) $pb.checkItemFailed(v, _i.qualifiedMessageName);
  }

  // Warning here
  String get value => $_getS(0, '');
  set value(String v) { $_setString(0, v); }
  bool hasValue() => $_has(0);
  void clearValue() => clearField(1);
}

我在value属性上遇到错误,因为不清楚它是获取/设置标准 Dart 字符串还是 Proto 消息字符串。

我无法更改原型,因此我尝试更改导入并在需要的地方添加前缀:

import 'dart:core' show int, bool, double, List, Map, override;
import 'dart:core' as core;

core.String get value => $_getS(0, '');
set value(core.String v) { $_setString(0, v); 

但这并不理想,因为我不想修改生成的代码,有没有更正确的方法来做到这一点?

以下错误副本:

Error: The argument type 'String (.../Framework.pb.dart)' can't be assigned to the parameter type 'String (C:\src\flutter\bin\cache\pkg\sky_engine\lib\core\string.dart)'. (argument_type_not_assignable at (.../Framework.pb.dart:50)

原型片段:

syntax = "proto3";

message String {
    string value = 1;
}

标签: dartprotocol-buffers

解决方案


推荐阅读