Flutter GetX 无法将 Set<CustomClass> 分配给 RxSet<CustomClass>

Flutter GetX can't assign Set<CustomClass> to RxSet<CustomClass>

我正在开发一个应用程序并遇到了一个问题,该问题不会导致错误,但让我非常沮丧。

情况是我有一个默认初始化为空 Set 的 CustomClass 对象的 RxSet。当我从服务器获取数据时,我想将结果分配给这个集合。正如 GetX 所建议的那样,我应该去 myRxSet = dataFetchedFromServer。这给了我一个编译时错误。 myRxSet.value = dataFetchedFromServer 仍然有效,但提供了一个我不应该分配给 .value 属性.

的信息

示例代码如下所示

RxSet<MyCustomClass> myCustomClassEntries = Set<MyCustomClass>().obs;

Future<void> syncData() async {
   myCustomClassEntries = await _fetchDataFromServer(); // this gives me compile time error
   myCustomClassEntries.value = await _ fetchDataFromServer(); // this gives me a warning that RxSet is not intented to be used this way.
}

GetX 版本:^4.3.4 颤动版本:2.2.3 飞镖版本:2.13.4

知道我做错了什么吗?

编辑


_fetchDataFromServer() 在这种情况下无关紧要,只是想为问题提供一些背景信息。就这么简单:

RxSet<MyCustomClass> myCustomClassEntries = Set<MyCustomClass>().obs;

// This line gives me a compile time error. It says Set<MyCustomClass> can't be assigned to RxSet<MyCustomClass>
myCustomClassEntries = new Set<MyCustomClass>();

// This line works, just like everywhere else with GetX, but says .value is no longer intented to be used on RxList, RxSet or RxMap. It recommends to use the syntax above, which gives the error.
myCustomClassEntries.value = new Set<MyCustomClass();

来自 GetX 更新日志

更改:您不需要访问基元的“.value”属性。对于字符串,您需要插值。对于 num、int、double,您将拥有正常的运算符,并将其用作飞镖类型。这样,.value 可以专门用于 ModelClasses。示例:

var name = "Jonny" .obs;
// usage:
Text ("$name");

var count = 0.obs;
// usage:
increment() => count ++;
Text("$count");

因此:自本版本起,List、Map、Set、num、int、double 和 String 将不再使用 .value 属性。

注意:更改不是中断更改,但是,您可能错过了文档的详细信息,因此如果您遇到以下消息:“成员 'value' 只能在子类的实例成员中使用'rx_list.dart'“您只需从列表中删除”.value“属性,一切都会按计划进行。地图和集合也是如此。

简而言之,在Getx中使用list时,不需要使用.value

...
myCustomClassEntries = Set<MyCustomClass>().obs; // just add .obs and treat it like a regular list. 
final object = MyCustomClass();
myCustomClassEntries.add(object); // no error here and not using .value

我要求使用 _fetchDataFromServer() 函数,因为它对您要执行的操作很重要 return。但无论如何,return 一个可观察的 Set<MyCustomClass>() 然后你不会有类型转换错误。

后续问题更新:

只是 return 来自 _fetchDataFromServer 函数的 RxSet<MyCustomClass>,所以你有匹配的类型。

Future<RxSet<MyCustomClass>> _fetchDataFromServer() async {
  final tempList = Set<MyCustomClass>().obs;
// ... your code that populates list from server
  return tempList;
}

您不需要清除列表。下面将仅使用函数中 return 编辑的内容来更新 myCustomClassEntries

myCustomClassEntries = await _fetchDataFromServer();