Flutter中async/await执行异常,按钮加载状态切换失效求助
问题原因与解决方法
你的按钮加载状态无法正常维持的核心问题在于:ontap回调函数没有返回Future,导致await widget.ontap()根本不会等待异步任务完成,代码会立刻执行setState(() { loading = false; }),所以加载指示器刚出现就消失了。
修复步骤
1. 修改Continue组件的回调参数类型
将ontap的类型从Function改为Future Function(),明确要求它是一个返回Future的异步函数:
class Continue extends StatefulWidget { const Continue({Key? key, required this.ontap}) : super(key: key); // 更新参数类型为Future函数 final Future Function() ontap; @override State<Continue> createState() => _ContinueState(); } class _ContinueState extends State<Continue> { bool loading = false; @override Widget build(BuildContext context) { return InkWell( onTap: () async { setState(() { loading = true; }); // 现在await会正确等待异步任务完成 await widget.ontap(); setState(() { loading = false; }); }, // 其余组件代码保持不变 child: Container( width: 180.w, height: 50.h, decoration: BoxDecoration( color: Theme.of(context).primaryColorDark, borderRadius: const BorderRadius.all(Radius.circular(4)), ), child: Padding( padding: EdgeInsets.all(8.sp), child: Center( child: loading == true ? CircularProgressIndicator( color: Theme.of(context).primaryColor, ) : ResponsiveText( text: 'Continue', maxLines: 1, centered: true, size: 16, style: TextStyle(color: Theme.of(context).primaryColor), ), ), ), ), ); } }
2. 修改回调函数为返回Future的异步函数
使用Future.delayed替代Timer,它会直接返回一个Future,让await能够正确等待:
ontap: () async { // 等待3秒,Future.delayed会返回Future await Future.delayed(const Duration(seconds: 3)); setState(() { otpActive = true; }); },
关于whenCompleted的使用
如果你需要在任务完成后执行额外操作,可以直接使用Future的whenCompleted方法,比如:
onTap: () async { setState(() { loading = true; }); await widget.ontap().whenCompleted(() { // 任务完成后可执行的额外逻辑 print("任务已完成"); }); setState(() { loading = false; }); },
内容的提问来源于stack exchange,提问作者Noobdeveloper
相关产品推荐
相关产品推荐

