6
votes

Comment vérifier si le widget s'est monté en flutter

Donc, dans mon application, je veux faire une requête Ajax dès que le widget est monté, pas dans initState () . Similaire à ComponentWillMount () dans react


1 commentaires

Ceci et ceci pourrait aider.


4 Réponses :


3
votes

Je ne pense pas que ce soit actuellement possible.

Voici la propriété montée : https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart#L974

  /// After creating a [State] object and before calling [initState], the
  /// framework "mounts" the [State] object by associating it with a
  /// [BuildContext]. The [State] object remains mounted until the framework

Et voici quand _element est défini: https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart#L3816 a>

_state._element = this

Et je ne vois aucun crochet autour de ce code qui nous informerait.

Pourquoi ne pas utiliser initState de toute façon? C'est probablement ce que tu veux. Voici le commentaire au-dessus de la propriété monté : https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart#L967

bool get mounted => _element != null;


0 commentaires

8
votes

si le widget n'a pas été monté , revenez. Faites-le avant la méthode setState

if (mounted) {
   //Do something
};
setState(() {});

ou

if (!mounted) return;
setState(() {});


0 commentaires

1
votes
   onPressed: () {
      if (mounted) {
        print("mounted");
        setState(
          () => counter(),
        );
      } else {
        print("unmounted");
      }
    },
Fact: One should only implement setState() method after checking “if(mounted)” which helps to avoid error like, setState() called after dispose().

0 commentaires

0
votes

Procédez simplement comme suit.

if (this.mounted) {
        setState(() {
         //Your code
        });
}


0 commentaires