Search code examples
flutterdartnavigationloading

How load another screen after tapping on the button?


I want to make something like loading screen between screens.

Actually I have made Options Screen, where you can choose difficulty and number of questions. enter image description here

When you tap on the button and choose difficulty (like on screenshot) you should have loading screen. How can I make it? Then after some time it should navigate to Quiz Screen with questions.

I have tried put Timer inside initState() below

Navigator.pop(context);

but it doesn't work.

Also I want to use Loading Animation Widget, to look this better.

My code

void _startQuiz() async {
    setState(() {
      processing = true;
    });
    try {
      List<Question> questions =
          await getQuestions(widget.category, _numberOfQuestions, _difficulty);
      Navigator.pop(context);
      

      Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (_) => QuizScreen(
                    questions: questions,
                    category: widget.category,
                  )));
      
    } catch (e) {
      print(e.toString());
      
      setState(() {
        processing = false;
      });
    }
  }

Thanks for help.


Solution

  • What i get from your issue was, you want to show Loading once getQuestions still in progress, if i'm correct here is my simply suggestion

      bool loading = false;
    
      @override
      Widget build(BuildContext context) {
        super.build(context);
        return Scaffold(
             body: loading ? YourLoadingScreenWidget : <Your Menu Widget>; //
          )
        );
      }
    
      void _startQuiz() async {
        setState(() {
          processing = true;
          loading = true; //Enable loading before getQuestions
        });
        try {
          List<Question> questions =
              await getQuestions(widget.category, _numberOfQuestions, _difficulty);
          //Navigator.pop(context); //I'm not sure why you pop the screen
          setState(() {
            loading = false; 
          });
          
    
          Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                  builder: (_) => QuizScreen(
                        questions: questions,
                        category: widget.category,
                      )));
          
        } catch (e) {
          print(e.toString());
          
          setState(() {
            loading = false; 
            processing = false;
          });
        }
      }