You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:03:32