繁体   English   中英

Flutter-在另一个小部件中将 MaterialPageRoute 作为参数传递

[英]Flutter- pass MaterialPageRoute as parameter in another widget

我想将 MaterialPageRoute 作为参数传递到另一个页面。 就像如果想将onPressed((){})传递到其他页面,我们将其声明为

FirstPage({
    this.onPressed,
  });
final GestureTapCallback onPressed;

如何将MaterialPageRoute(builder: (context) => SecondPage())作为参数传递给其他页面?

这是一种方法:

class MyApp extends StatelessWidget {

  const MyApp({Key? key}): super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FirstPage(
        materialPageRoute: MaterialPageRoute(builder: (context) => const SecondPage()),
      )
    );
  }
}

class FirstPage extends StatelessWidget {

  const FirstPage({
    Key? key,
    required this.materialPageRoute,
  }): super(key: key);

  final MaterialPageRoute materialPageRoute;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextButton(
          onPressed: () => Navigator.of(context).push(materialPageRoute),
          child: const Text('Navigate to SecondPage'),
        ),
      )
    );
  }
}

class SecondPage extends StatelessWidget {

  const SecondPage({Key? key}): super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: const Center(
        child: Text('Second Page'),
      ),
    );
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM