问题
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.
Actual Code (you can compile it without problems just add http: ^0.12.0 in dependencies).
Photos of the actual system:
First step of login
Progress bar that I want to implement (I want to kick the raisedButton for a while)
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();
},
)
],
),
)),
);
}
}
回答1:
Just change the code as follow,
// 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())
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.
Then writing async loginn() method with await keyword will wait for that method to get executed.
Then after it will change the progress indicator state to false using setState method which will re-render the UI again.
回答2:
Yes you can, just called setState() method if the user clicked the button.
bool _loading = false;
!_loading ? RaisedButton(
child: Text('Log in'),
onPressed: (){
_loginn();
setState(() => _loading = true);
},
) : CircularProgressIndicator();
If the user clicked, then it will setState _loading bool to true and the widget will rebuild to Progress Indicator
And also, call setState method again after you get your data.
来源:https://stackoverflow.com/questions/59507960/async-await-to-do-circularprogressindicator-in-a-login-page-in-flutter