在Dart/Flutter中如何将int转换为RxInt?解决类型转换报错
你之前的写法错误在于直接把原生int强制转换成RxInt,但两者是完全不同的类型——RxInt是可观察的包装类,并非int的子类,所以强制类型转换必然失败。
正确实现方式
方式1:直接用获取到的int值创建RxInt
Future<RxInt> getCounterFromPrefs() async { final prefs = await SharedPreferences.getInstance(); // 从SharedPreferences取值,未存储过则用默认值0 final counter = prefs.getInt("counter") ?? 0; // 通过.obs扩展方法将int转为RxInt return counter.obs; }
方式2:先初始化RxInt,再更新其值
Future<RxInt> getCounterFromPrefs() async { // 先创建默认值为0的RxInt final rxCounter = 0.obs; final prefs = await SharedPreferences.getInstance(); final storedCounter = prefs.getInt("counter"); // 如果有存储值,更新RxInt的value属性 if (storedCounter != null) { rxCounter.value = storedCounter; } return rxCounter; }
错误原因说明
- 第一种错误写法里
i = n as RxInt,试图把int类型的n强制转为RxInt,类型不兼容导致报错。 - 第二种错误写法里
n = preferences.getInt("counter") as RxInt?,同样是跨类型强制转换,Dart不允许这种无继承/实现关系的类型转换,所以抛出type 'int' is not a subtype of type 'RxInt'错误。
内容的提问来源于stack exchange,提问作者Mihir Parmar
相关产品推荐
相关产品推荐

