flutter - 如何从异步函数中获取价值并在 UI 中更新任何更改?
问题描述
我是 Flutter 的新手。我正在做一个项目,并使用 HIVE 进行本地存储,使用 Provider 进行状态管理。我做了一个购物车部分,我将所有添加到本地存储的购物车中的菜串起来,我想在该屏幕上显示购物车的总量。这是我的 HIVE 对象:
@HiveType(typeId: 0)
class DishHive extends HiveObject {
DishHive({
required this.dishId,
required this.dishName,
required this.dishDescription,
required this.dishImage,
required this.dishPrice,
this.quantity,
});
@HiveField(0)
String dishId;
@HiveField(1)
String dishName;
@HiveField(2)
String dishDescription;
@HiveField(3)
List<int> dishImage;
@HiveField(4)
int dishPrice;
@HiveField(5)
int? quantity;}
我还创建了一个提供程序类的函数,它将帮助我使用 HIVE 进行 CRUD 操作,以及一个为我提供购物车总数的函数。
class CartFunctions extends ChangeNotifier {
int Total = 0;
List<DishHive> cartItems = [];
void setTotal(int total) {
Total = total;
}
void onChange() {
notifyListeners();
}
getCartTotal() async {
List<DishHive> listDish = [];
int TotalofCart = 0;
final box = await Hive.openBox<DishHive>('toCart');
listDish = box.values.toList();
listDish.forEach((element) {
TotalofCart = TotalofCart + (element.dishPrice * element.quantity!);
});
print('Total: $TotalofCart');
setTotal(TotalofCart);
//notifyListeners();
return Total;
}
下面是我要获取总数的地方。
trailing: FutureBuilder<dynamic>(
future: cartObj.getCartTotal(),
builder: (BuildContext context,
AsyncSnapshot<dynamic> snap) {
if (snap.connectionState ==
ConnectionState.active) {
return CircularProgressIndicator(
color: const Color(0xFF265cff),
);
} else if (snap.hasData) {
print('Final Total: ${snap.data}');
return Text(snap.data.toString());
}
return Text('0');
},
),
我面临的问题是在第二个代码片段中声明的总值始终保持为 0。它只在getCartTotal函数内给我总值,但只有在我刷新或来回切换页面时才会在 UI 中更新。我要实时更新。我也是 Stack Overflow 的新手,如果我在某个地方错了,请告诉我。提前致谢。
解决方案
所以问题是你在cartObj.getCartTotal()
重建树时不断打电话,这正在重置你的总数,而未来建设者的未来永远不会得到解决。您希望将未来存储在状态中并监视未来,而不是直接在构建方法中调用它。
class _SomeWidgetState extends State<SomeWidget> {
/// state variable for storing the future
Future<int>? cartTotal;
@override
void initState() {
super.initState();
/// store the future in state
cartTotal = cartObj.getCartTotal();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<dynamic>(
/// use the stored future with the future builder...
future: cartTotal,
builder: (BuildContext context, AsyncSnapshot<dynamic> snap) {
if (snap.connectionState == ConnectionState.active) {
return CircularProgressIndicator(
color: const Color(0xFF265cff),
);
} else if (snap.hasData) {
print('Final Total: ${snap.data}');
return Text(snap.data.toString());
}
return Text('0');
},
);
}
}
推荐阅读
- javascript - 代码在控制台中有效,但在 Hackerrank 中无效
- r - R Shiny Modules - 不能将类型“闭包”强制为类型字符的向量
- android - Firebase PhoneAuth 不工作(当另一个身份验证方法工作时)Android
- android - 在这个 Flutter 示例中格式化文本的最佳方式是什么?
- python-3.x - 如何用 Marshmallow 序列化嵌套字典?
- javascript - 如何在 css 图像上添加图像扩展名?
- glib - 如何释放 GSettings 使用的资源?
- node.js - 在 NestJS CQRS 配方中处理“事件溯源”的首选方式
- css - 显示弹性宽度的问题
- java - 通过意图保存两个活动之间的状态