I'm new to flutter. I'm trying to build register and login app. I need to make circularprogressindicator before running app . it worked fine before I added a Navigator. after I addedd Navigator it not worked. Can anyone help me please.
class Loading extends StatefulWidget {
@override
_LoadingState createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
void _loadUserInfo() async {
String token = await getToken();
if (token == '') {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => Login()), (route) => false);
} else {
ApiResponse response = await getUserDetails();
if (response.error == null) {
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context)=>Home()), (route) => false);
} else if (response.error == unauthorized) {
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context)=>Login()), (route) => false);
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content : Text('${response.error}'),
));
}
}
}
@override
void initState() {
_loadUserInfo();
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height,
color: Colors.white,
child: Center(
child: CircularProgressIndicator(),
),
);
}
}
CodePudding user response:
you can use Future
function
Future _loadUserInfo() async {}
and in the body use like this:
FutureBuilder(
future: _loadUserInfo(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return Container(
height: MediaQuery.of(context).size.height,
color: Colors.white,
child: const Center(
child: CircularProgressIndicator(),
),
);
},
);
this will show indicator but i suggest you to work with snapshot
if (snapshot.hasError) {
// here indicator should be
}else{
// in the else you need to show login
}
research about future to read more
CodePudding user response:
In the current code in initstate you have called a method that checks for the token. I assume that's from shared preferences . When you first install the app it would give you an empty string(assuming again). Then the first condition check is that if its empty you are navigating to login page.
String token = await getToken();
if (token == '') {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => Login()), (route) => false);
}
To force to display the progress indicator you can add a future delayed before navigating like
String token = await getToken();
if (token == '') {
Future.delayed(Duration(seconds:4), (){
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => Login()), (route) => false);
});
}
CodePudding user response:
You did not create any functions to disable the progress indicator after navigation.