【问题标题】:How to know pop event happened inside Nested Widget in Flutter如何知道在 Flutter 的嵌套小部件中发生了弹出事件
【发布时间】:2020-04-26 19:54:06
【问题描述】:

我目前正在构建应用程序,我需要使用嵌套路由来保持一个屏幕相同并在不同的屏幕上路由。我想当第二条路线被弹出时,我可以改变扩展的值来填满整个屏幕。 Gist in Github。 这是代码示例:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(body: MyHomePage()),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> with RouteAware {
  bool rightPanelIsShown;
  Widget child;
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey();
  final RouteObserver<PageRoute> _routeObserver = RouteObserver<PageRoute>();

  @override
  void initState() {
    super.initState();
    setState(() {
      rightPanelIsShown = false;
      child = Container();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _routeObserver.subscribe(this, ModalRoute.of(context));
    setState(() {
      child = Container();
    });
  }

  @override
  void didPop() {
    super.didPop();
    print('popped');
    setState(() {
      rightPanelIsShown = false;
    });
  }

  @override
  void dispose() {
    print("dis");
    _routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Center(
              child: FlatButton(
                color: Colors.blue,
                onPressed: () => setState(() {
                  rightPanelIsShown = !rightPanelIsShown;
                  child = Page1();
                }),
                child: Text(
                  'Open Right Panel',
                  style: TextStyle(color: Colors.white, fontSize: 25.0),
                ),
              ),
            ),
          ),
          rightPanelIsShown
              ? Expanded(
                  flex: 1,
                  child: Navigator(
                    onGenerateRoute: (route) => MaterialPageRoute(
                      builder: (context) => child,
                    ),
                  ),
                )
              : Container(),
        ],
      ),
    );
  }
}

class Page1 extends StatelessWidget {
  const Page1({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Text(
            'Page1',
            style: TextStyle(
              fontSize: 30.0,
            ),
          ),
          _buildGoToButton(context),
          _buildBackbutton(context)
        ],
      ),
    );
  }

  FlatButton _buildGoToButton(BuildContext context) {
    return FlatButton(
      color: Colors.green,
      onPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => Page2(),
          ),
        );
      },
      child: Text(
        'Go To Page 2',
        style: TextStyle(fontSize: 21.0),
      ),
    );
  }

  FlatButton _buildBackbutton(BuildContext context) {
    return FlatButton(
      color: Colors.red,
      onPressed: () {
        Navigator.pop(context);
      },
      child: Text(
        'Close',
        style: TextStyle(fontSize: 21.0),
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  const Page2({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Text(
            'Page2',
            style: TextStyle(
              fontSize: 30.0,
            ),
          ),
          _buildBackButton(context)
        ],
      ),
    );
  }

  FlatButton _buildBackButton(BuildContext context) {
    return FlatButton(
      color: Colors.red,
      onPressed: () {
        Navigator.pop(context);
      },
      child: Text(
        'Close',
        style: TextStyle(fontSize: 21.0),
      ),
    );
  }
}

Screencast of built upto

当单击右侧面板 Page1 上的关闭时,它还应该更改父级的状态。 谢谢,

更新

在 João Soares 的帮助下工作

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(body: MyHomePage()),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> with RouteAware {
  bool rightPanelIsShown;
  Widget child;
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey();
  final RouteObserver<PageRoute> _routeObserver = RouteObserver<PageRoute>();

  @override
  void initState() {
    super.initState();
    setState(() {
      rightPanelIsShown = false;
      child = Container();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _routeObserver.subscribe(this, ModalRoute.of(context));
    setState(() {
      child = Container();
    });
  }

  @override
  void didPop() {
    super.didPop();
    print('popped');
    setState(() {
      rightPanelIsShown = false;
    });
  }

  @override
  void dispose() {
    print("dis");
    _routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Center(
              child: Column(
                children: <Widget>[
                  FlatButton(
                    color: Colors.blue,
                    onPressed: () => setState(() {
                      rightPanelIsShown = !rightPanelIsShown;
                      child = Page1(
                        callback: onPop,
                      );
                    }),
                    child: Text(
                      'Open Right Panel 1',
                      style: TextStyle(color: Colors.white, fontSize: 25.0),
                    ),
                  ),
                  FlatButton(
                    color: Colors.blue,
                    onPressed: () => setState(() {
                      rightPanelIsShown = !rightPanelIsShown;
                      child = Page3(
                        callback: onPop,
                      );
                    }),
                    child: Text(
                      'Open Right Panel 2',
                      style: TextStyle(color: Colors.white, fontSize: 25.0),
                    ),
                  ),
                ],
              ),
            ),
          ),
          rightPanelIsShown
              ? Expanded(
                  flex: 1,
                  child: PanelView(
                    child: child,
                  ),
                )
              : Container(),
        ],
      ),
    );
  }

  onPop(value) {
    print("popped");
    setState(() {
      rightPanelIsShown = false;
    });
  }
}

class PanelView extends StatefulWidget {
  final Widget child;

  PanelView({Key key, this.child}) : super(key: key);

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

class _PanelViewState extends State<PanelView> {
  @override
  Widget build(BuildContext context) {
    return Navigator(
      onGenerateRoute: (route) {
        return MaterialPageRoute(builder: (context) {
          return Container(
            child: widget.child,
          );
        });
      },
    );
  }
}

class Page1 extends StatelessWidget {
  final Function callback;
  const Page1({Key key, this.callback}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Text(
            'Page1',
            style: TextStyle(
              fontSize: 30.0,
            ),
          ),
          _buildGoToButton(context),
          _buildBackbutton(context)
        ],
      ),
    );
  }

  FlatButton _buildGoToButton(BuildContext context) {
    return FlatButton(
      color: Colors.green,
      onPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => Page2(),
          ),
        );
      },
      child: Text(
        'Go To Page 2',
        style: TextStyle(fontSize: 21.0),
      ),
    );
  }

  FlatButton _buildBackbutton(BuildContext context) {
    return FlatButton(
      color: Colors.red,
      onPressed: () {
        callback('hello');
        Navigator.of(context).pop();
      },
      child: Text(
        'Close',
        style: TextStyle(fontSize: 21.0),
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  const Page2({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Text(
            'Page2',
            style: TextStyle(
              fontSize: 30.0,
            ),
          ),
          _buildBakButton(context)
        ],
      ),
    );
  }

  FlatButton _buildBakButton(BuildContext context) {
    return FlatButton(
      color: Colors.red,
      onPressed: () {
        Navigator.pop(context);
      },
      child: Text(
        'Close',
        style: TextStyle(fontSize: 21.0),
      ),
    );
  }
}

class Page3 extends StatelessWidget {
  final Function callback;
  const Page3({Key key, this.callback}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Text(
            'Page2',
            style: TextStyle(
              fontSize: 30.0,
            ),
          ),
          _buildBakButton(context)
        ],
      ),
    );
  }

  FlatButton _buildBakButton(BuildContext context) {
    return FlatButton(
      color: Colors.red,
      onPressed: () {
        callback('page3');
        Navigator.pop(context);
      },
      child: Text(
        'Close',
        style: TextStyle(fontSize: 21.0),
      ),
    );
  }
}

如果有更好的解决方案,我不必将回调传递给 PanelView 的每个子小部件,例如左侧面板中有 2 个按钮,它确定哪个小部件将显示在右侧面板中,其中按钮子确定子小部件设置它处于状态。

【问题讨论】:

  • 在关闭事件时返回一个 int 值(例如页码)
  • 您能否说明如何/在哪里执行此操作。在 Page1 上,我可以使用 Navigator.pop(context, 1) 发送值,但是在哪里使用它以及如何使用它?
  • 这些行是强制性的吗???右面板显示? Expanded( flex: 1, child: Navigator( onGenerateRoute: (route) => MaterialPageRoute( builder: (context) => child, ), ), ) : Container(), **** 因为我建议你使用按钮来导航
  • 是的,因为这是我发现获得所需输出的唯一方法。您可以检查原始问题中的 gif 链接以获取输出。因为我需要固定左侧,而右侧有自己的路由。左侧可以有多个按钮,可以更改右侧的小部件,然后右侧会有嵌套的小部件。
  • 如果您需要将数据从导航器传回主视图,我建议您使用与直接在主视图上集成导航器小部件不同的解决方案。我会写一些我认为会做你想做的代码,但它可能需要一些配合。

标签: flutter flutter-navigation


【解决方案1】:

如果您在同一个类中编写所有代码,则只需从导航器中的主类调用一个函数:

小部件

Navigator(
  onGenerateRoute: (route) => MaterialPageRoute(
    builder: (context) {
      return Container(
        color: Colors.orange,
        child: RaisedButton(
          child: Text('Close panel'),
          onPressed: () {
            panelClosed("I'm sending data back");
            Navigator.of(context).pop();
          }
        )
      );
    }
  ),
),

方法

void panelClosed(data){
  print("Panel closed");
  setState(() {
    message = data;
  });
}

如果您希望 Navigator 位于单独的类中,则只需将要调用的函数从父类传递给子类,如下所示:

父类中的小部件

Expanded(
  flex: 1,
  child: PanelView(callBack: panelClosed,)
)

方法

void panelClosed(data){
  print("Panel closed");
  setState(() {
    message = data;
  });
}

带有导航器的类

class PanelView extends StatefulWidget {
  final Function callBack;

  PanelView({this.callBack});

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

class _PanelViewState extends State<PanelView> {
  @override
  Widget build(BuildContext context) {
    return Navigator(
      onGenerateRoute: (route) {
        return MaterialPageRoute(
          builder: (context) {
            return Container(
              color: Colors.orange,
              child: Column(
                children: <Widget>[
                  Text('panel 2'),
                  RaisedButton(
                    child: Text('Close'),
                    onPressed: () {
                      widget.callBack('send any data here');
                      Navigator.of(context).pop();
                    }
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }
}

【讨论】:

  • 谢谢,我会在示例项目和主要产品上试用它并在此处更新。
  • 酷。我会等待您的反馈。
  • 感谢您的解决方案,我更新了有问题的代码和Gist。如果有更好的解决方案,例如子小部件将发生变化的情况,我不必将回调函数传递给面板视图的每个新子小部件。
猜你喜欢
  • 2020-01-08
  • 2021-10-16
  • 1970-01-01
  • 2023-01-20
  • 2021-11-30
  • 1970-01-01
  • 2013-10-03
  • 2020-03-08
  • 2018-12-04
相关资源
最近更新 更多