【问题标题】:is there any way to add CircularProgressIndicator while wating to get response form dio request有什么方法可以添加 CircularProgressIndicator 以获取响应表单 dio 请求
【发布时间】:2021-06-29 19:11:19
【问题描述】:

这是授权文件:

    Future attempt(String token) async {
        try {
          Dio.Response response = await dio().get(
            '/user',
            options: Dio.Options(
                headers: {'Authorization': 'Bearer $token'},
                followRedirects: false,
                validateStatus: (status) {
                  return status! < 500;
                }),
          );
    'get user info '
          _user = User.fromJson(json.decode(response.toString()));
          _authenticated = true;
          // return response;
        } catch (e) {
          _authenticated = false;
        }
        notifyListeners();
      }

在这个 main.dart 文件中,我想使用一个 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.authenticated) {
                return Text('You are logged in!');
              } else  {
                return Text('You are not logged in!');
              }
               }
            },
          )),
        );
      }
    }

【问题讨论】:

  • 您可以显示带有圆形指示器的对话框,直到您收到请求的响应

标签: flutter dart mobile


【解决方案1】:

您可以使用变量来检查加载是否结束 首先设置 loading = true 然后在 dio set loading = false 之后 当 loading = true 时,显示一个 CircularProgressIndicator,当加载 false 时显示你想要的任何东西

【讨论】:

    【解决方案2】:

    您可以使用FutureBuilder 小部件来调用您的异步函数,并在此期间显示CircularProgressIndicator

    FutureBuilder<bool>(
        future: myFuture,
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
             if (snapshot.data) {
                // Your stuff if you're logged
             } else {
                   return CircularProgressIndicator(),
             }
       }
    )
    

    【讨论】:

    • 指标以任何方式启动并且不会消失
    • 这个代码:FutureBuilder(future: authenticated, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return Center( child: Consumer (builder: (context, auth, child) { if (auth.authenticated) { return Text('You are logged in!'); } ); } else { return Center(child: CircularProgressIndicator());
    猜你喜欢
    • 2021-05-20
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 2019-12-27
    相关资源
    最近更新 更多