yitzih
yitzih

Reputation: 3118

Extending setState to only run if mounted

I'm trying to write an extension method to avoid issues with calling setState when a Widget isn't mounted. The code looks something like this:

import 'package:flutter/widgets.dart';

extension SetStateIfMounted on State {
  void setStateIfMounted(VoidCallback onMounted, [ VoidCallback onNotMounted ]) {
    if (mounted) {
      setState(onMounted);
    } else {
      LogService.logger.w('Widget not mounted. setState being ignored');
      if (onNotMounted != null)
        onNotMounted();
    }
  }
}

Is this a bad idea? Is there some reason I wouldn't always want to check if a widget is mounted before calling setState()?

Upvotes: 0

Views: 679

Answers (1)

rickimaru
rickimaru

Reputation: 2500

Why not create an abstract class that extends State and overrides setState(...).

abstract class SafeState<T extends StatefulWidget> extends State<T> {
  @override
  void setState(VoidCallback fn) {
    if (!mounted) {
      return;
    }

    super.setState(fn);
  }
}

In your StatefulWidget's state, extend SafeState instead of State.

Upvotes: 2

Related Questions