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

Flutter Dio请求等待响应期间如何添加CircularProgressIndicator加载提示

Flutter Dio请求时展示加载动画的实现方法

1. 修改Auth状态类新增加载状态标记

首先在你的Auth类中新增加载状态相关变量,修改attempt方法,在请求发起前标记为加载中,请求结束(无论成功失败)后关闭加载状态,代码示例如下:

// Auth类中新增变量
bool _isLoading = false;
bool get isLoading => _isLoading;

Future attempt(String token) async {
    // 发起请求前标记加载中
    _isLoading = true;
    notifyListeners();
    try {
      Dio.Response response = await dio().get(
        '/user',
        options: Dio.Options(
            headers: {'Authorization': 'Bearer $token'},
            followRedirects: false,
            validateStatus: (status) {
              return status! < 500;
            }),
      );
      _user = User.fromJson(json.decode(response.toString()));
      _authenticated = true;
    } catch (e) {
      _authenticated = false;
    } finally {
      // 请求结束后关闭加载状态
      _isLoading = false;
      notifyListeners();
    }
  }

2. 修改main.dart的渲染逻辑

在Consumer的builder中优先判断加载状态,加载中时返回CircularProgressIndicator组件即可,修改后的代码如下:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text(widget.title),
    ),
    drawer: NavDrawer(),
    body: Center(child: Consumer<Auth>(
      builder: (context, auth, child) {
        // 优先判断加载状态
        if (auth.isLoading) {
          return const CircularProgressIndicator();
        }
        if (auth.authenticated) {
          return const Text('You are logged in!');
        } else  {
          return const Text('You are not logged in!');
        }
      },
    )),
  );
}

内容的提问来源于stack exchange,提问作者kefah omran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 14:36:08