触发从窗口小部件到状态对象的函数

azi*_*iza 7 dart flutter

这是场景的简化版本:

class ParentWdiegt extends StatelessWidget{
//
//
floatinActionButton: FloatingActionButtonWidget(onPressed:()=>CustomWidgetState.someMethod(someValue))
//
//somewhere in the ParentWidget tree
child: CustomWidget() //is stateful
}
Run Code Online (Sandbox Code Playgroud)

CustomWidgetState

class CustomWidgetState extends State<CustomWidget>{
//trigger this function when FAB is pressed in parent widget
someMethod(SomeValue) {//}
}
Run Code Online (Sandbox Code Playgroud)

someMethod在不使用FAB的情况下按下FAB时,是否有任何方式可以在状态对象中显示InheritedWidget

Rém*_*let 23

同时GlobalKey允许轻松访问任何小部件的状态; 躲开它.窗口小部件应直接与其他部件进行交互.这是Flutter的核心原则之一.

Flutter使用反应式编程.小部件通过提交事件与彼此通信的位置.而不是直接编辑所需的小部件.

显而易见的好处是小部件保持独立.并且可能有数十个小部件可以使用相同的原理相互通信.

我已经在这里举例说明如何使两个不同的小部件共享一个共同的可编辑值.

如果要调用方法,则使用相同的原则:A ListenableStream小部件之间共享.但没有使用AnimatedWidgetStreamBuilder听取.相反,我们将手动进行监听(这需要更多的样板)来触发自定义功能.

这是一个使用的例子Stream.

import 'dart:async';
import 'package:flutter/material.dart';

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  final changeNotifier = new StreamController.broadcast();

  @override
  void dispose() {
    changeNotifier.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Column(
      children: <Widget>[
        new AnotherWidget(
          shouldTriggerChange: changeNotifier.stream,
        ),
        new RaisedButton(
          child: new Text("data"),
          onPressed: () => changeNotifier.sink.add(null),
        )
      ],
    );
  }
}

class AnotherWidget extends StatefulWidget {
  final Stream shouldTriggerChange;

  AnotherWidget({@required this.shouldTriggerChange});

  @override
  _AnotherWidgetState createState() => _AnotherWidgetState();
}

class _AnotherWidgetState extends State<AnotherWidget> {
  StreamSubscription streamSubscription;

  @override
  initState() {
    super.initState();
    streamSubscription = widget.shouldTriggerChange.listen((_) => someMethod());
  }

  @override
  didUpdateWidget(AnotherWidget old) {
    super.didUpdateWidget(old);
    // in case the stream instance changed, subscribe to the new one
    if (widget.shouldTriggerChange != old.shouldTriggerChange) {
      streamSubscription.cancel();
      streamSubscription = widget.shouldTriggerChange.listen((_) => someMethod());
    }
  }

  @override
  dispose() {
    super.dispose();
    streamSubscription.cancel();
  }

  void someMethod() {
    print('Hello World');
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,只要执行实例化的单击someMethod,AnotherWidget就会调用.RaisedButton_ParentWidgetState