首页 > 解决方案 > async/await 在 Flutter 的登录页面中执行 CircularProgressIndicator

问题描述

我在登录页面中遇到了 CircularProgressIndicator 的问题。我想这样做。当用户点击“登录”按钮时,我希望应用程序创建一个 CircularProgressIndicator 并启动 raiseButton Text 并添加 CircularProgessIdnicator,然后我的应用程序从我的网络服务获取数据我想停止 CircularProgessIndicator。有小费吗?谢谢。

实际代码(您可以毫无问题地编译它,只需在依赖项中添加 http: ^0.12.0)。

实际系统照片:

登录第一步

我想实现的进度条(我想踢一下raisedButton)

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;


void main() => runApp(MaterialApp(home:MyApp()));

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool estaCargando = false;
  TextEditingController user = TextEditingController();
  TextEditingController phone = TextEditingController();
  Future<List> _loginn() async {
    var url = "https://pruebasxaviervelez.000webhostapp.com/login.php";
    final response = await http
        .post(url, body: {"usuario": user.text, "telefono": phone.text});
    print(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          color: Colors.pink,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  height: 100,
                  width: 100,
                  child: TextField(
                    controller: user,
                    decoration: InputDecoration(hintText: 'username'),
                  ),
                ),
                Container(
                  height: 100,
                  width: 100,
                  child: TextField(
                    controller: phone,
                    decoration: InputDecoration(hintText: 'password'),
                  ),

                ),
                RaisedButton(
                  child: Text('Log in'),
                  onPressed: (){
                    _loginn();
                  },
                )
              ],
            ),
          )),
    );
  }
}

标签: flutterflutter-layoutflutter-animationflutter-web

解决方案


只需将代码更改如下,

// Inside your _MyAppState class
bool isLoading = false;

// Inside your build method
isLoading ? RaisedButton(
                  child: Text('Log in'),
                  onPressed: async(){
                    setState((){
                       isLoading=true;
                    });
                    await _loginn();
                    setState((){
                       isLoading=false;
                    });
                  },
                )
           : Center(child:CircularProgressIndicator())

当您按下按钮时,首先我们通过 setState 方法将进度指示器的加载状态更改为 true,这将重新渲染 UI。

然后使用 await 关键字编写 async loginn() 方法将等待该方法被执行。

然后,它将使用 setState 方法将进度指示器状态更改为 false,该方法将再次重新渲染 UI。


推荐阅读