我在返回 Future 的类的末尾调用 notifyListeners() ,就在 return 语句之前。由notifyListeners发起的action在调用return和后续语句处理之前没有完全完成,导致错误。看来notifyListeners 以某种方式异步完成。
我在另一个论坛上询问了这个问题,并被告知这是一个常见的颤动错误,尤其是与动画相关的问题。在我看来,我的语法有问题的可能性更大。有没有人遇到过这个“错误”?
我尝试同时使用 .then() 和 async/await。两者都有相同的结果。
Future<bool> updateProduct(Map<String, dynamic> updatedProduct)
Run Code Online (Sandbox Code Playgroud)
...
return http
.put(
'https://chocolate-f3e81.firebaseio.com/products/${newProduct.serverID}.json',
body: json.encode(newProductMap))
.then<bool>((http.Response response) {
if (response.statusCode == 200 || response.statusCode == 201) {
_products[selectedProductIndex] = newProduct;
setIsLoading(false);
print('model selectedProductIndex ${selectedProductIndex}');
print('model selectedProductServerID ${_selectedProductServerID}');
notifyListeners();
return true;
Run Code Online (Sandbox Code Playgroud)
我希望notifyListeners() 启动的所有内容在执行“return true”之前完成。这不会发生,而是执行返回操作,其他代码继续运行并领先于 notifyListeners() 启动的代码。
事实上,它notifyListeners()实际上是异步运行的,因为它通过使用来调度微任务scheduleMicrotask()实际上以异步方式运行,因为它通过调用所有注册的侦听器来
根据官方文档
通过此函数注册的回调始终按顺序执行,并保证在其他异步事件(如计时器事件或 DOM 事件)之前运行。
只想到一个可能适合您的情况的丑陋await Future.delayed(Duration(milliseconds: 300))解决方案,即在之前运行return true,以便给它一点时间来完成其任务。
| 归档时间: |
|
| 查看次数: |
1274 次 |
| 最近记录: |