title: How do I reset my controller when I come back or finish?
body: <p><a href="https://i.stack.imgur.com/AkjXF.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AkjXF.gif" alt="enter image description here" /></a></p>
  <p>I have a QuestionController class extends <code>GetxController</code></p>
  <p>When I exit the Page using the controls, I want it to stop working (because it is still running in the background) and to start again if I come back to that page.</p>
  <p>I've tried: I added these after the route of the <code>ScoreScreen()</code> (in <code>nextQuestion ()</code>) :</p>
  <pre><code>_isAnswered = false;
  _questionNumber.value = 1; 
  </code></pre>
  <p>I reset the values ​​before going to the score page. It may work if you go to the score page, but if you come back earlier, it won't. (up side Question num/4 does not work here). So this way is not suitable.</p>
  <p>What is the way I can stop and reset it when the page exits?</p>
  <p>Controller class code:</p>
  <pre><code>class QuestionController extends GetxController
      with SingleGetTickerProviderMixin {
    PageController _pageController;
  
    PageController get pageController =&gt; this._pageController;
  
    List&lt;Question&gt; _questions = questions_data
        .map(
          (e) =&gt; Question(
              id: e[&quot;id&quot;],
              question: e[&quot;question&quot;],
              options: e[&quot;options&quot;],
              answer: e[&quot;answer_index&quot;]),
        )
        .toList();
  
    List&lt;Question&gt; get questions =&gt; this._questions;
  
    bool _isAnswered = false;
  
    bool get isAnswered =&gt; this._isAnswered;
  
    int _correctAns;
  
    int get correctAns =&gt; this._correctAns;
  
    int _selectedAns;
  
    int get selectedAns =&gt; this._selectedAns;
  
    RxInt _questionNumber = 1.obs;
  
    RxInt get questionNumber =&gt; this._questionNumber;
  
    int _numOfCorrectAns = 0;
  
    int get numOfCorrectAns =&gt; this._numOfCorrectAns;
  
    @override
    void onInit() {
      _pageController = PageController();
      super.onInit();
    }
  
    @override
    void onClose() {
      super.onClose();
      _pageController.dispose();
    }
  
    void checkAns(Question question, int selectedIndex) {
      _isAnswered = true;
      _correctAns = question.answer;
      _selectedAns = selectedIndex;
  
      if (_correctAns == _selectedAns) _numOfCorrectAns++;
  
      update();
  
      Future.delayed(Duration(seconds: 2), () {
        nextQuestion();
      });
    }
  
    void nextQuestion() {
      if (_questionNumber.value != _questions.length) {
        _isAnswered = false;
        _pageController.nextPage(
            duration: Duration(milliseconds: 300), curve: Curves.ease);
      } else {
        Get.off(ScoreScreen(correctNum: _numOfCorrectAns)); // GetMaterialApp()
  
        // _isAnswered = false;
  
        _numOfCorrectAns = 0;
  
        //_questionNumber.value = 1;
  
      }
    }
  
    void updateTheQuestionNum(int index) {
      _questionNumber.value = index + 1;
    }
  }
  </code></pre>
  <p>Full code below</p>
  <pre><code>import 'package:flutter/material.dart';
  import 'dart:async';
  import 'package:get/get.dart';  // get: ^3.25.4
  
  //  QuizPage()     ===============&gt; 50. line      (Question 1/4) 81. line
  //  QuestionCard()  ==============&gt; 116. line
  //  Option()   ===================&gt; 163. line
  //  QuestionController()  ========&gt; 218. line
  //  ScoreScreen() ================&gt; 345. line
  
  void main() =&gt; runApp(new MyApp());
  
  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return GetMaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(canvasColor: Colors.blue),
        home: HomeScreen(),
      );
    }
  }
  
  class HomeScreen extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text(&quot;Home Page&quot;),
        ),
        body: Center(
          child: InkWell(
            onTap: () {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) =&gt; QuizPage()));
            },
            child: Container(
              padding: EdgeInsets.all(22),
              color: Colors.green,
              child: Text(
                &quot;Go Quiz Page&quot;,
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ),
      );
    }
  }
  
  class QuizPage extends StatelessWidget {
    const QuizPage({
      Key key,
    }) : super(key: key);
  
    @override
    Widget build(BuildContext context) {
      QuestionController _questionController = Get.put(QuestionController());
  
      return Scaffold(
        appBar: AppBar(
          title: Text(&quot;Quiz Page&quot;),
        ),
        body: Stack(
          children: [
            SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 16,
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16),
                    child: Obx(
                      () =&gt; Center(
                        child: RichText(
                            text: TextSpan(
                                // text,style default adjust here OR:children[TextSpan(1,adjust 1),TextSpan(2,adjust 2),..]
                                text:
                                    &quot;Question ${_questionController._questionNumber.value}&quot;,
                                style: TextStyle(
                                    fontSize: 33, color: Colors.white70),
                                children: [
                              TextSpan(
                                  text:
                                      &quot;/${_questionController._questions.length}&quot;,
                                  style: TextStyle(fontSize: 25))
                            ])),
                      ),
                    ),
                  ),
                  Divider(color: Colors.white70, thickness: 1),
                  SizedBox(
                    height: 16,
                  ),
                  Expanded(
                    child: PageView.builder(
                      physics: NeverScrollableScrollPhysics(),
                      controller: _questionController._pageController,
                      onPageChanged: _questionController.updateTheQuestionNum,
                      itemCount: _questionController.questions.length,
                      itemBuilder: (context, index) =&gt; QuestionCard(
                        question: _questionController.questions[index],
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      );
    }
  }
  
  class QuestionCard extends StatelessWidget {
    final Question question;
  
    const QuestionCard({
      Key key,
      @required this.question,
    }) : super(key: key);
  
    @override
    Widget build(BuildContext context) {
      QuestionController _controller = Get.put(QuestionController());
  
      return Container(
        margin: EdgeInsets.only(left: 16, right: 16, bottom: 16),
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(25),
          color: Colors.white,
        ),
        child: Column(
          children: [
            Text(
              question.question,
              style: TextStyle(fontSize: 22),
            ),
            SizedBox(
              height: 8,
            ),
            Flexible(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    ...List.generate(
                        question.options.length,
                        (index) =&gt; Option(
                            text: question.options[index],
                            index: index,
                            press: () =&gt; _controller.checkAns(question, index)))
                  ],
                ),
              ),
            )
          ],
        ),
      );
    }
  }
  
  class Option extends StatelessWidget {
    final String text;
    final int index;
    final VoidCallback press;
  
    const Option({
      Key key,
      @required this.text,
      @required this.index,
      @required this.press,
    }) : super(key: key);
  
    @override
    Widget build(BuildContext context) {
      return GetBuilder&lt;QuestionController&gt;(
          init: QuestionController(),
          builder: (q) {
            Color getRightColor() {
              if (q.isAnswered) {
                if (index == q._correctAns) {
                  return Colors.green;
                } else if (index == q.selectedAns &amp;&amp;
                    q.selectedAns != q.correctAns) {
                  return Colors.red;
                }
              }
              return Colors.blue;
            }
  
            return InkWell(
              onTap: press,
              child: Container(
                //-- Option
                margin: EdgeInsets.only(top: 16),
                padding: EdgeInsets.all(16),
                decoration: BoxDecoration(
                    color: getRightColor(),
                    borderRadius: BorderRadius.circular(16)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      &quot;${index + 1}. $text&quot;,
                      style: TextStyle(fontSize: 16, color: Colors.white),
                    ),
                  ],
                ),
              ),
            );
          });
    }
  }
  
  class QuestionController extends GetxController
      with SingleGetTickerProviderMixin {
    PageController _pageController;
  
    PageController get pageController =&gt; this._pageController;
  
    List&lt;Question&gt; _questions = questions_data
        .map(
          (e) =&gt; Question(
              id: e[&quot;id&quot;],
              question: e[&quot;question&quot;],
              options: e[&quot;options&quot;],
              answer: e[&quot;answer_index&quot;]),
        )
        .toList();
  
    List&lt;Question&gt; get questions =&gt; this._questions;
  
    bool _isAnswered = false;
  
    bool get isAnswered =&gt; this._isAnswered;
  
    int _correctAns;
  
    int get correctAns =&gt; this._correctAns;
  
    int _selectedAns;
  
    int get selectedAns =&gt; this._selectedAns;
  
    RxInt _questionNumber = 1.obs;
  
    RxInt get questionNumber =&gt; this._questionNumber;
  
    int _numOfCorrectAns = 0;
  
    int get numOfCorrectAns =&gt; this._numOfCorrectAns;
  
    @override
    void onInit() {
      _pageController = PageController();
      //_pageController.addListener(() { _questionNumber.value = _pageController.page.round()+1; });
      super.onInit();
    }
  
    @override
    void onClose() {
      super.onClose();
      _pageController.dispose();
    }
  
    void checkAns(Question question, int selectedIndex) {
      _isAnswered = true;
      _correctAns = question.answer;
      _selectedAns = selectedIndex;
  
      if (_correctAns == _selectedAns) _numOfCorrectAns++;
  
      update();
  
      Future.delayed(Duration(seconds: 2), () {
        nextQuestion();
      });
    }
  
    void nextQuestion() {
      if (_questionNumber.value != _questions.length) {
        _isAnswered = false;
        _pageController.nextPage(
            duration: Duration(milliseconds: 300), curve: Curves.ease);
      } else {
        Get.off(ScoreScreen(correctNum: _numOfCorrectAns)); // GetMaterialApp()
  
        // _isAnswered = false;
  
        _numOfCorrectAns = 0;
  
        //_questionNumber.value = 1;
  
      }
    }
  
    void updateTheQuestionNum(int index) {
      _questionNumber.value = index + 1;
    }
  }
  
  class Question {
    final int id, answer;
    final String question;
    final List&lt;String&gt; options;
  
    Question({
      @required this.id,
      @required this.question,
      @required this.options,
      @required this.answer,
    });
  }
  
  const List questions_data = [
    {
      &quot;id&quot;: 1,
      &quot;question&quot;: &quot;Question 1&quot;,
      &quot;options&quot;: ['option A', 'B', 'C', 'D'],
      &quot;answer_index&quot;: 3,
    },
    {
      &quot;id&quot;: 2,
      &quot;question&quot;: &quot;Question 2&quot;,
      &quot;options&quot;: ['option A', 'B', 'C', 'D'],
      &quot;answer_index&quot;: 2,
    },
    {
      &quot;id&quot;: 3,
      &quot;question&quot;: &quot;Question 3&quot;,
      &quot;options&quot;: ['option A', 'B', 'C', 'D'],
      &quot;answer_index&quot;: 0,
    },
    {
      &quot;id&quot;: 4,
      &quot;question&quot;: &quot;Question 4&quot;,
      &quot;options&quot;: ['option A', 'B', 'C', 'D'],
      &quot;answer_index&quot;: 0,
    },
  ];
  
  class ScoreScreen extends StatelessWidget {
    final int correctNum;
  
    ScoreScreen({@required this.correctNum});
  
    @override
    Widget build(BuildContext context) {
      QuestionController _qController = Get.put(QuestionController());
  
      return Scaffold(
        body: Stack(
          fit: StackFit.expand,
          children: [
            Column(
              children: [
                Spacer(
                  flex: 2,
                ),
                Text(
                  &quot;Score&quot;,
                  style: TextStyle(fontSize: 55, color: Colors.white),
                ),
                Spacer(),
                Text(
                  &quot;${correctNum * 10}/${_qController.questions.length * 10}&quot;,
                  style: TextStyle(fontSize: 33, color: Colors.white),
                ),
                Spacer(
                  flex: 2,
                ),
                InkWell(
                  onTap: () =&gt; Get.back(),
                  borderRadius: BorderRadius.circular(16),
                  child: Container(
                    padding: EdgeInsets.all(16),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(16),
                        color: Colors.white24),
                    child: Text(
                      &quot;Back to Home Page&quot;,
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                Spacer(),
              ],
            ),
          ],
        ),
      );
    }
  }
  </code></pre>