Как я могу передать обратный вызов другому StatefulWidget? - PullRequest
0 голосов
/ 15 мая 2018

Например, у меня есть два StatefulWidget для мониторинга одного и того же метода обратного вызова.Как мне это сделать?В случае, если у меня есть более трех StatefulWidget для мониторинга его событий?

class WidgetOne extends StatefulWidget {
  @override
  _WidgetOneState createState() => new _WidgetOneState();
}

class _WidgetOneState extends State<WidgetOne> {

  // this is the callback, the widget two want listen the callback too
  bool _onNotification(ScrollNotification notification){

  }

  @override
  Widget build(BuildContext context) {
    return new Column(
      children: <Widget>[
        new NotificationListener(child: new ListView(shrinkWrap: true,),
          onNotification: _onNotification),
        new WidgetTwo()
      ],
    );
  }
}

class WidgetTwo extends StatefulWidget {
  @override
  _WidgetTwoState createState() => new _WidgetTwoState();
}

class _WidgetTwoState extends State<WidgetTwo> {

  // in this,How Can I get the callback in WidgetOne?
  @override
  Widget build(BuildContext context) {
    return new Container();
  }
}

Ответы [ 2 ]

0 голосов
/ 15 мая 2018

Ваше решение может быть возможно с помощью setState() и передать вашу функцию состояния в конструктор WidgetTwo.Я сделал пример ниже, основная идея этого примера в том, что у меня есть MyHomePage в качестве основного виджета и MyFloatButton (который я хочу настроить как еще один StatefulWidget), поэтому при нажатииFAB мне нужно вызвать функцию счетчика приращений в MyHomePage.Давайте посмотрим ниже, как я это делаю.

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  //Consider this function as your's _onNotification and important to note I am using setState() within :)
  void _incrementCounter() { 
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          widget.title,
          style: TextStyle(color: Colors.white),
        ),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button $_counter times:',
              style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
            ),
          ],
        ),
      ),
      floatingActionButton: new MyFloatButton(_incrementCounter),//here I am calling MyFloatButton Constructor passing _incrementCounter as a function
    );
  }
}

class MyFloatButton extends StatefulWidget {

  final Function onPressedFunction;

  // Here I am receiving the function in constructor as params
  MyFloatButton(this.onPressedFunction);

  @override
  _MyFloatButtonState createState() => new _MyFloatButtonState();
}

class _MyFloatButtonState extends State<MyFloatButton> {
  @override
  Widget build(BuildContext context) {
    return new Container(
      padding: EdgeInsets.all(5.0),
      decoration: new BoxDecoration(color: Colors.orangeAccent, borderRadius: new BorderRadius.circular(50.0)),
      child: new IconButton(
        icon: new Icon(Icons.add),
        color: Colors.white,
        onPressed: widget.onPressedFunction,// here i set the onPressed property with widget.onPressedFunction. Remember that you should use "widget." in order to access onPressedFunction here!
      ),
    );
  }
}

Теперь рассмотрим MyHomePage как WidgetOne, MyFloatButton как WidgetTwo и функцию _incrementCounter как _onNotification.Надеюсь, вы добьетесь того, чего хотите :)

(я сделал пример в общем, чтобы каждый мог понять, согласно сценарию, с которым они сталкиваются)

0 голосов
/ 15 мая 2018

Вы не можете и не должны. Виджеты никогда не должны зависеть от архитектуры других виджетов.

У вас есть две возможности:

  • Слияние WidgetTwo и WidgetOne. Разделять их не имеет смысла (по крайней мере, с тем, что вы предоставили).
  • Изменить WidgetTwo, чтобы взять ребенка. И добавьте, что ListView как потомок WidgetTwo. Чтобы он мог обернуть список в свой собственный NotificationListener.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...