How to know pop event happened inside Nested Widget in Flutter

。_饼干妹妹 提交于 2021-02-05 11:31:49

问题


I am currently building app where I need to use Nested Routing keeping one screen same and routing on different one. I want to when that second route is popped so that I can change value of expanded to fill whole screen. Gist in Github. Here is code sample:

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

When click on close on right panel Page1 it should also change state of parent. Thanks,

Update

Working with help of 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),
      ),
    );
  }
}

If there is better solution where I don't have to pass callback to every child widget of PanelView like if have 2 buttons in left panel and it determines which widget will be shown in right panel where button child determines child widget setting it in state.


回答1:


If you are writing all your code in the same class, you can just call a function from your main class inside the Navigator:

Widget

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();
          }
        )
      );
    }
  ),
),

Method

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

If instead you want your Navigator in a separate class, then you just need to pass down the function you want to call from the parent class to the child class like this:

Widget in parent class

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

Method

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

The class with the navigator

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();
                    }
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }
}


来源:https://stackoverflow.com/questions/59660086/how-to-know-pop-event-happened-inside-nested-widget-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!