Set state for variable error; This widget has been unmounted, so the State no longer has a context (and should be considered defunct)

198

i just changed the variables initialization and it worked.

String _selectedYear = "";
String _selectedSem = "";

and also added this logic to the setState

setState(() {
     _selectedSem = value!;
});

this did the trick for me, try it out and see

Share:
198
George Oti-Adjei
Author by

George Oti-Adjei

Updated on January 04, 2023

Comments

  • George Oti-Adjei
    George Oti-Adjei over 1 year

    I'm fairly new to Flutter and I have a page where I take in two inputs in a search fieldstone them in different variables(_selectedYear and _selectedSem) and based on the inputs I create a url. On creating the two search fields and running it , if I input in the second field before the first one, I have no error but if I input in the first field before the second field this error pops up.

    This widget has been unmounted, so the State no longer has a context (and should be considered defunct). Consider canceling any active work during dispose or using the getter mounted to determine if the state is still active.

    Here's a screenshot of the page:

    Here is the code.

    class _TestrState extends State<Testr> {
      String _selectedYear;
      String _selectedSem;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            elevation: 0,
            backgroundColor: Colors.white,
            title: const Text(
              'Testr',
              style: TextStyle(
                color: Colors.black,
              ),
            ),
            flexibleSpace: Container(
              decoration: const BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.centerLeft,
                      end: Alignment.bottomRight,
                      colors: [Colors.green, Colors.limeAccent])),
            ),
          ),
          body: Container(
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    height: MediaQuery.of(context).size.height * 0.64,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Padding(
                          padding: EdgeInsets.all(20.0),
                          child: Text(
                            'Select a Year',
                            style: TextStyle(fontSize: 16, color: Colors.blueGrey),
                          ),
                        ),
                        Container(
                          width: double.infinity,
                          margin: const EdgeInsets.symmetric(horizontal: 20),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.2),
                                blurRadius: 10,
                                offset: const Offset(0, 10),
                              ),
                            ],
                          ),
                          child: SearchField(
                            hint: 'Search for Year',
                            searchInputDecoration: InputDecoration(
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: Colors.blueGrey.shade200,
                                  width: 1,
                                ),
                                borderRadius: BorderRadius.circular(10),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  width: 2,
                                  color: Colors.blue.withOpacity(0.8),
                                ),
                                borderRadius: BorderRadius.circular(10),
                              ),
                            ),
                            maxSuggestionsInViewPort: 4,
                            itemHeight: 50,
                            suggestionsDecoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(10),
                            ),
                            onTap: (value) {
                              setState(() {
                                _selectedYear = value;
                              });
    
                              if (kDebugMode) {
                                print(value);
                              }
                            },
                            suggestions: const [
                              'Year One',
                              'Year Two',
                              'Year Three',
                              'Year Four',
                            ],
                          ),
                        ),
                        const Padding(
                          padding: EdgeInsets.all(20.0),
                          child: Text(
                            'Select a Semester',
                            style: TextStyle(fontSize: 16, color: Colors.blueGrey),
                          ),
                        ),
                        Container(
                          width: double.infinity,
                          margin: const EdgeInsets.symmetric(horizontal: 20),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.2),
                                blurRadius: 10,
                                offset: const Offset(0, 10),
                              ),
                            ],
                          ),
                          child: SearchField(
                            hint: 'Search for Semester',
                            searchInputDecoration: InputDecoration(
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: Colors.blueGrey.shade200,
                                  width: 1,
                                ),
                                borderRadius: BorderRadius.circular(10),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  width: 2,
                                  color: Colors.blue.withOpacity(0.8),
                                ),
                                borderRadius: BorderRadius.circular(10),
                              ),
                            ),
                            maxSuggestionsInViewPort: 4,
                            itemHeight: 50,
                            suggestionsDecoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(10),
                            ),
                            onTap: (value) {
                              setState(() {
                                _selectedSem = value;
                              });
    
                              if (kDebugMode) {
                                print(value);
                              }
                            },
                            suggestions: const [
                              'Afghanistan',
                              'Turkey',
                              'Germany',
                              'France',
                              'Italy',
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    height: 90,
                    padding: const EdgeInsets.only(right: 20, left: 20, bottom: 20),
                    decoration: const BoxDecoration(
                      color: Colors.white,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        _selectedYear == null
                            ? const Text(
                                'Select a Year and a Semester to Continue',
                                style:
                                    TextStyle(fontSize: 14, color: Colors.blueGrey),
                              )
                            : Text(_selectedYear + "->" + _selectedSem,
                                style: TextStyle(
                                    fontSize: 16,
                                    color: Colors.grey.shade800,
                                    fontWeight: FontWeight.w600)),
                        MaterialButton(
                          onPressed: () {
                            CreateURL(_selectedYear, _selectedSem);
                          },
                          color: Colors.black,
                          minWidth: 50,
                          height: 50,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(50),
                          ),
                          padding: const EdgeInsets.all(0),
                          child: const Icon(
                            Icons.arrow_forward_ios,
                            color: Colors.blueGrey,
                            size: 24,
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        );
      }
    }
    

    Ive tried placing the setstate in an 'if(mounted)' and that didn't work after looking at other similar questions.

    • Ashutosh singh
      Ashutosh singh about 2 years
      if(mounted){ //call set state here }
    • George Oti-Adjei
      George Oti-Adjei about 2 years
      Hello, Already tried this before even posting the question. Didn't work for me
  • George Oti-Adjei
    George Oti-Adjei about 2 years
    Just tried this. Didn't work unfortunately. I also initialized the variable at the beginning of the code when I created the class.
  • George Oti-Adjei
    George Oti-Adjei about 2 years
    Thank you so much. Worked for me . Why do you have to intialize it to an empty string though? What made you use this approach?
  • Moro Owusu Afriyie
    Moro Owusu Afriyie about 2 years
    @GeorgeOti-Adjei because String is a non nullable type means it can't be null. With null safety, Dart has no way of knowing if you had actually assigned a variable to _selectedYear. so it's always better to assign a value or if you can use the late keyword to initialize it something like late String _selectedYear or if you still want it to be null when intialized you can do String? _selectedYear otherwise it won't have any value and it will give you problems
  • Mayur Devmurari
    Mayur Devmurari about 2 years
    you try with null safety?