Home > Software engineering >  Set state for variable error; This widget has been unmounted, so the State no longer has a context (
Set state for variable error; This widget has been unmounted, so the State no longer has a context (

Time:04-20

A Good day to everyone. So 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.Click here

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.

Anyone mind helping me out?

CodePudding user response:

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

CodePudding user response:

I'm not sure but once you try this way. first, initialize value to a variable and then refresh state

_selectedYear = value;
setState(() {});

or if you are using flutter version 2.5.3 or higher then you need to initialize variable or migrate to null safety.

  • Related