La administración de estado compartido (InheritedWidget) es fácil de usar

Gestión de estado compartido: uso simple de InheritedWidget

InheritedWidgetEs un componente funcional muy importante en Flutter, que proporciona una forma de compartir datos de arriba a abajo en el árbol de widgets.

InheritedWidgeLas funciones en t e Reactin contextson similares y pueden realizar la transferencia de datos de componentes cruzados. InheritedWidgetLa dirección de la transferencia de datos en el árbol de widgets es de arriba a abajo.

Primero mira InheritedWidgetel código fuente,

  • En la construcción de InheritedWidget, se debe pasar un hijo, y este hijo es un sub-widget que necesita usar datos compartidos
  • updateShouldNotify Este método abstracto debe ser implementado por subclases
abstract class InheritedWidget extends ProxyWidget {
    
    
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const InheritedWidget({
    
     super.key, required super.child });

  
  InheritedElement createElement() => InheritedElement(this);

  /// Whether the framework should notify widgets that inherit from this widget.
  ///
  /// When this widget is rebuilt, sometimes we need to rebuild the widgets that
  /// inherit from this widget but sometimes we do not. For example, if the data
  /// held by this widget is the same as the data held by `oldWidget`, then we
  /// do not need to rebuild the widgets that inherited the data held by
  /// `oldWidget`.
  ///
  /// The framework distinguishes these cases by calling this function with the
  /// widget that previously occupied this location in the tree as an argument.
  /// The given widget is guaranteed to have the same [runtimeType] as this
  /// object.
  
  bool updateShouldNotify(covariant InheritedWidget oldWidget);
}

Para definir datos compartidos para la aplicación de muestra "contador" InheritedWidget, debe heredar de InheritedWidget, de la siguiente manera:

class CounterWidget extends InheritedWidget {
    
    
  // 1.需要共享的数据
  final int counter;

  // 2.定义构造方法 传入最新的 counter值
  CounterWidget({
    
    this.counter, Widget child}): super(child: child);

  // 3.获取组件最近的当前InheritedWidget
  static CounterWidget of(BuildContext context) {
    
    
    // 沿着Element树, 去找到最近的CounterElement, 从Element中取出Widget对象
    return context.dependOnInheritedWidgetOfExactType();
  }

  // 4.绝对要不要回调State中的didChangeDependencies
  // 如果返回true: 执行依赖当期的InheritedWidget的State中的 didChangeDependencies
  
  bool updateShouldNotify(CounterWidget oldWidget) {
    
    
    return oldWidget.counter != counter;
  }
}
  • Los datos a compartir son un contador de tipo int

  • Asigne un valor al contador en la construcción, y el niño es el widget que necesita usar los datos

  • Define un método of, que comienza a encontrar los ancestros a través del contexto.CounterWidget

  • updateShouldNotifyEl método es comparar lo antiguo y lo nuevo CounterWidget, y si actualizar el Widget que depende de él

    Si devuelve verdadero: La ejecución depende del estado del InheritedWidget actualdidChangeDependencies

Para usar en el ejemplo CounterWidget, defina el subcomponente ShowDataWidget para usar datos compartidos:

class _HomePageState extends State<HomePage> {
    
    
  int _counter = 100;

  
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("InheritedWidget"),
      ),
      body: CounterWidget(//使用CounterWidget 将需要使用数据widget包裹
        counter: _counter,
        child: Center(
          child:  ShowDataWidget(),//在ShowDataWidget 中去使用共享的数据
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
    
    
          setState(() {
    
    
            _counter++; 
          });
        },
      ),
    );
  }
}



class ShowDataWidget extends StatefulWidget {
    
    
  
  _ShowDataWidgetState createState() => _ShowDataWidgetState();
}

class _ShowDataWidgetState extends State<ShowDataWidget> {
    
    

  
  void didChangeDependencies() {
    
    
    super.didChangeDependencies();
    print("执行了ShowDataWidget中的didChangeDependencies");
  }

  
  Widget build(BuildContext context) {
    
    
    int counter = CounterWidget.of(context).counter;

    return Card(
      color: Colors.red,
      child: Text("当前计数: $counter", style: TextStyle(fontSize: 30),),CounterWidget
    );
  }
}

Podemos ver eso:

  • Después de presionar el botón de acción flotante aquí, llame a setState para volver a llamar al método de compilación de _HomePageState, y luego vuelva a crear y CounterWidgetpase el último valor del contador.

  • ShowDataWidgetObtenga la instancia llamando CounterWidgetal método **de** en y CounterWidgetobtenga el contador de datos compartidos

     int counter = CounterWidget.of(context).counter;
    
  • Vemos que el método _ShowDataWidgetStateen didChangeDependenciesse llama

    El marco Flutter llamará didChangeDependenciesal método cuando cambie la "dependencia". ¡Y esta "dependencia" se refiere a si el widget secundario usa los datos del widget heredado en el widget principal! Si se usa, significa que el subwidget tiene dependencias; si no se usa, significa que no tiene dependencias. ¡Este mecanismo permite que los subcomponentes se actualicen cuando cambia el InheritedWidget dependiente! Por ejemplo, cuando cambia el tema, la configuración regional (idioma), etc., se llamará al método didChangeDependencies del sub-widget que depende de él.

    2022-11-09 13:11:06.175 14203-14233/com.example.learn_flutter I/flutter: 执行了_ShowData01State中的didChangeDependencies
    2022-11-09 13:11:07.383 14203-14233/com.example.learn_flutter I/flutter: 执行了_ShowData01State中的didChangeDependencies
    2022-11-09 13:11:08.248 14203-14233/com.example.learn_flutter I/flutter: 执行了_ShowData01State中的didChangeDependencies
    2022-11-09 13:11:08.999 14203-14233/com.example.learn_flutter I/flutter: 执行了_ShowData01State中的didChangeDependencies
    

El efecto es el siguiente:
inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/MrLizuo/article/details/127770093
Recomendado
Clasificación