Search code examples
flutternavigatorprogress-indicator

How to add circularprogressindicator before run flutter app


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(),
      ),
    );
  }
}

Solution

  • 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);
         });
         
        }