Home > Blockchain >  Dart Unhandled Exception: setState() called after dispose() in flutter
Dart Unhandled Exception: setState() called after dispose() in flutter

Time:08-30

I have a page on which I display data via BloC. I added the isLoading variable to display the loading indicator, which is true after two seconds, this value changes to false and the loading indicator disappears and the data is displayed. But I got an error because I use setState(). Tell me how to fix this error?

Widget _child(Size size, BuildContext context, double topPadding) {
    return BlocBuilder<MycarsCubit, MycarsState>(
      builder: (context, stateElectricvehicles) {
        final ElectricvehiclesCubit cubit =
            BlocProvider.of<ElectricvehiclesCubit>(context);

        if (stateElectricvehicles is MycarsInitial) {
          carNumber.text = stateElectricvehicles.number;
          carNumber.selection = TextSelection.fromPosition(
            TextPosition(offset: carNumber.text.length),
          );

          if (stateElectricvehicles.id == 0) {
            savedCarId = stateElectricvehicles.id;
          }

          Future.delayed(const Duration(seconds: 2), () {
            setState(() {
              isLoading = false;
            });
          });

          final SharedPrefs prefs = SharedPrefs();
          return FutureBuilder<int?>(

enter image description here

CodePudding user response:

Always add a check mounted (available in StatefulWidget) before calling setState in async function.

          Future.delayed(const Duration(seconds: 2), () {
           if(mounted) {
            setState(() {
              isLoading = false;
            });
           }
          });

CodePudding user response:

See if this solves it:

 Future.delayed(const Duration(seconds: 2), () {
   // Wrap setState in an if:
   if (mounted) {
     setState(() {
        isLoading = false;
     });
   }
 });

This should make sure setState() is not called unless the context is still mounted.

In later versions of flutter lints, you will get a warning about this, saying something like "Do not use context over async gaps!". Meaning if you have an async delay, i.e. an "await", you have to check afterwards if the context is still alive before you use it.

  • Related