flutter - 通过 ChangeNotifierProvider 加载状态未显示
问题描述
这是我的代码。我想CircularprogressIndicator
在点击时显示SpeedDialChild
。所以我做ChangeNotifier
了如下。并CircularprogressIndicator
使用Consumer
. 但Consumer
不会更新我的用户界面。如何解决这个问题?
Widget build(BuildContext context) {
return ChangeNotifierProvider<loading>(
create: (_) => loading(),
child: Scaffold(
body: Stack(
children: [
Container(
child: GoogleMap(
initialCameraPosition: _currentlo,
),
),
Consumer<loading>(
builder: (context, value, child) => value.getloading() ?
Center(child: CircularProgressIndicator()) : Container(),
),
],
),
floatingActionButton: Builder(
builder: (BuildContext context){
return SpeedDial(
children: [
SpeedDialChild(
backgroundColor: Colors.white,
child: Icon(Icons.refresh, color: Colors.black,),
onTap: (){
Provider.of<loading>(context, listen: false).yesloading();
refreshMarkers();
Provider.of<loading>(context, listen: false).noloading();
}
),
],
);
},
),
),
);
}
class loading with ChangeNotifier{
bool _isloading = false;
bool getloading(){
return _isloading;
}
void yesloading(){
_isloading = true;
notifyListeners();
}
void noloading(){
_isloading = false;
notifyListeners();
}
}
解决方案
发生这种情况是因为您立即(同步)再次将加载变量设置为 false:
Provider.of<loading>(context, listen: false).noloading();
如果删除此行,将显示加载指示器。
你可能想打电话给await
你。refreshMarkers
如果refreshMarkers
返回 a Future
,您应该能够做到这一点:
onTap: () async {
Provider.of<loading>(context, listen: false).yesloading();
await refreshMarkers();
Provider.of<loading>(context, listen: false).noloading();
}
现在,您将在refreshMarkers
完成时看到加载指示器。
了解 Dart 中的异步编程。
此外,您可以并且可能应该查看Effective Dart:样式指南,以使您的代码具有可读性。
推荐阅读
- pentaho - Kettle:在存储库中运行并预览执行
- javascript - 对扩展 Array 的类的意外构造函数调用
- corda - Corda 默认对构建的 jar 进行签名,但坚持我应该添加签名凭据或将 enable 设置为 false
- java - Java 日历:字段 DATE、DATE_OF_YEAR 究竟包含什么?
- kubernetes - 如何处理可突发的 k8s pod 的 CPU 争用?
- python - 重命名 Django 用户字段
- github - Gradle maven-publish 插件在子项目上失败
- ios - 没有新的应用程序二进制提交。新的应用内购买产品卡在“等待审核”?
- java - 如何使用 aws-java-sdk 2.0 删除非空 S3 存储桶
- python - 为re.sub替换参数转义Python正则表达式字符串?