async/await 在 Flutter 的登录页面中执行 CircularProgressIndicator [英] async/await to do CircularProgressIndicator in a Login Page in Flutter
问题描述
我在登录页面中遇到了 CircularProgressIndicator 的问题.我想这样做.当用户点击登录"按钮时,我希望应用程序创建一个 CircularProgressIndicator 并启动 raiseButton Text 并添加 CircularProgessIdnicator,然后我的应用程序从我的网络服务获取数据我想停止 CircularProgessIndicator.有小费吗?谢谢.
I am facing problems with the CircularProgressIndicator in a login page. I would like to do this. When the users tap in "log in" button I want that the app makes a CircularProgressIndicator and kick the raisedButton Text and add the CircularProgessIdnicator, and after that my app get the data from my webservice I want to stop the CircularProgessIndicator. Any Tips? thanks.
实际代码(您可以毫无问题地编译它,只需在依赖项中添加 http: ^0.12.0).
Actual Code (you can compile it without problems just add http: ^0.12.0 in dependencies).
实际系统照片:
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();
},
)
],
),
)),
);
}
}
推荐答案
改代码如下,
// 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.
When you press on the button, first we have changed the loading state of the progress indicator to true via setState method which will re-render the UI.
然后用 await 关键字编写 async loginn() 方法将等待该方法被执行.
Then writing async loginn() method with await keyword will wait for that method to get executed.
然后它将使用 setState 方法将进度指示器状态更改为 false,这将再次重新渲染 UI.
Then after it will change the progress indicator state to false using setState method which will re-render the UI again.
这篇关于async/await 在 Flutter 的登录页面中执行 CircularProgressIndicator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!