【问题标题】:Flutter - Use Notification to message other widgetsFlutter - 使用通知向其他小部件发送消息
【发布时间】:2019-03-10 03:45:36
【问题描述】:

我想在 StatefulWidget 中使用颤振通知与另一个 StatefulWidget 小部件进行通信。我在下面发布了一个示例,我觉得应该可以工作,但事实并非如此。当您单击“+”图标按钮时,它应该将通知发送到 subPage 小部件。目前,当您单击按钮时,似乎没有任何反应。我希望执行 onTitlePush() 函数。这是我第一次尝试通知,我必须有一些设置不正确。我在一个更大的应用程序中使用它,但下面的代码只是实现的一个示例。你能告诉我哪里出错了吗?

import 'package:flutter/material.dart';

void main() => runApp(TestApp());

class TestApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Notificaton Test',
      home: MainPage(),
    );
  }
}

class MyNotification extends Notification {
  final String title;

  const MyNotification({this.title});
}

class MainPage extends StatefulWidget {
  @override
  MainPageState createState() {
    return new MainPageState();
  }
}

class MainPageState extends State<MainPage> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Basic AppBar'),
          actions: <Widget>[
            // action button
            IconButton(
              icon: new Icon(Icons.add),
              onPressed: () {
                MyNotification(title: "Updated Text!")..dispatch(context);
              },
            ),
            // action button
          ],
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: new SubPage(),
        ),
      ),
    );
  }
}

class SubPage extends StatefulWidget {
  @override
  SubPageState createState() {
    return new SubPageState();
  }
}

class SubPageState extends State<SubPage> {
  String _text = "Click the Plus Icon";
  @override
  Widget build(BuildContext context) {
    return NotificationListener<MyNotification>(
      onNotification: onTitlePush,
      child: new Center(
          child: new Text(_text, style: new TextStyle(fontSize: 40.0))
      ),
    );
  }
  bool onTitlePush(MyNotification notification) {
    print("New item ${notification.title}");

    setState(() { _text = notification.title; });
    return true;
  }
}

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    通知与 BuildContext 相反。 通过通知,是孩子向他们的父母发送价值。

    通知不是全局。不是调度程序父级的小部件无法收听所述通知。

    因此,实际上您试图实现的目标无法通过通知来完成。

    有几种选择:

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2014-01-30
    • 2013-12-21
    • 2021-10-24
    • 2013-05-08
    相关资源
    最近更新 更多