简体   繁体   English

导航到 Flutter 中的新屏幕

[英]Navigate to a new screen in Flutter

How do you navigate to a new screen in Flutter?如何导航到 Flutter 中的新屏幕?

These questions are similar, but are asking more than I am.这些问题很相似,但问的比我多。

I am adding an answer below.我在下面添加一个答案。

Navigate to a new screen:导航到新屏幕:

Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));

where context is the BuildContext of a widget and NewScreen is the name of the second widget layout.其中context是小部件的 BuildContext , NewScreen是第二NewScreen部件布局的名称。

在此处输入图片说明

Code代码

main.dart main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home Screen')),
      body: Center(
        child: RaisedButton(
          child: Text(
            'Navigate to a new screen >>',
            style: TextStyle(fontSize: 24.0),
          ),
          onPressed: () {
            _navigateToNextScreen(context);
          },
        ),
      ),
    );
  }

  void _navigateToNextScreen(BuildContext context) {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));
  }
}

class NewScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('New Screen')),
      body: Center(
        child: Text(
          'This is a new screen',
          style: TextStyle(fontSize: 24.0),
        ),
      ),
    );
  }
}

See also也可以看看

Navigate to next screen with back using Navigator.push()使用Navigator.push()导航到下一个屏幕并返回

Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),);

Navigate to next screen without back using Navigator.pushReplacement()使用Navigator.pushReplacement()导航到下一个屏幕而不返回

Navigator.pushReplacement(
context,MaterialPageRoute(builder: (context) => SecondRoute()),);

To load new screens with Flutter pre-canned animations , use their respective transition classes.要使用 Flutter 预制动画加载新屏幕,请使用它们各自的过渡类。 For example:例如:

Container Transformation容器改造

在此处输入图片说明

Basically we have the first widget or screen transform into the next screen.基本上,我们将第一个小部件或屏幕转换为下一个屏幕。 For this we need to use OpenContainer .为此,我们需要使用OpenContainer The following code illustrates an item in a ListView transformed to its details page.以下代码说明了 ListView 中的一个项目转换为其详细信息页面。

  @override
  Widget build(BuildContext context) {
    return Card(
      color: Colors.white,
      elevation: 2.0,
      child: OpenContainer(
        transitionType: ContainerTransitionType.fadeThrough,
        closedColor: Theme.of(context).cardColor,
        closedElevation: 0.0,
        openElevation: 4.0,
        transitionDuration: Duration(milliseconds: 1500),
        openBuilder: (BuildContext context, VoidCallback _) => THENEXTSCREEN(),
        closedBuilder: (BuildContext _, VoidCallback openContainer) {
          return ListTile(
            leading: Icon(Icons.album),
            title: Text("ITEM NAME"),
          );
        },
      ),
    );
  }

Shared Axis共享轴

在此处输入图片说明

This transition is similar to that in Tab or Stepper.此转换类似于 Tab 或 Stepper 中的转换。 We need SharedAxisTransition , PageTransitionSwitcher , along with a state to model transition between active and previous page.我们需要SharedAxisTransitionPageTransitionSwitcher ,具有为激活状态和前一页之间的模式转型一起。 If we only switch between two pages we can use a simple boolean isFirstPage for it.如果我们只在两个页面之间切换,我们可以为它使用一个简单的布尔值isFirstPage Here's the snippet with Provider as state management:以下是 Provider 作为状态管理的片段:

  @override
  Widget build(BuildContext context) {
    return Consumer<YourState>(
      builder: (context, state, child) {
        return PageTransitionSwitcher(
          duration: const Duration(milliseconds: 1500),
          reverse: !state.isFirstPage, // STATE
          transitionBuilder: (
            Widget child,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
          ) {
            return SharedAxisTransition(
              child: child,
              animation: animation,
              secondaryAnimation: secondaryAnimation,
              transitionType: SharedAxisTransitionType.horizontal,
            );
          },
          child: state.isFirstPage? FIRSTPAGE() : SECONDPAGE(), // STATE
        );
      },
    );
  }

Note that in all these scenarios we don't use Navigator and MaterialPageRoute.请注意,在所有这些场景中,我们不使用 Navigator 和 MaterialPageRoute。 All these codes are derived from animations repo so you may want to check it out first.所有这些代码都来自动画存储库,因此您可能需要先查看一下。

onTap: () {
  Navigator.push(context,
      MaterialPageRoute(builder: (context) => NextScreenName()));
}

If you are familiar with web development this approach is similar to routing.如果您熟悉 Web 开发,则此方法类似于路由。

main.dart main.dart

void main() {
  setupLocator();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      routes: {
        '/' : (BuildContext context)=>HomePage(),
        '/register' : (BuildContext context)=>RegisterPage(),
      },
    );
  }
}

You can add button onPressed event from the homepage.dart to navigate register.dart as follows.您可以从homepage.dart添加按钮onPressed事件来导航register.dart如下。

onPressed: (){
    Navigator.pushReplacementNamed(context, '/register');
 },

Here is a full example of routes push / pop:这是路由推送/弹出的完整示例:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Routes',
      routes: {
        '/login': (BuildContext context) => Login(),
        // add another route here
        // '/register': (BuildContext context) => Register(),
      },
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Routes'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(
              onPressed: () {
                // This gives the back button:
                Navigator.of(context).pushNamed('/login');

                // This doesn't give the back button (it replaces)
                //Navigator.pushReplacementNamed(context, '/login');
              },
              child: Text('Login'),
            ),
          ],
        ),
      ),
    );
  }
}

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Login Page'),
        ),
        body: Center(
          child: RaisedButton(
            onPressed: () {
              // This will only work for pushNamed
              Navigator.of(context).pop();
            },
            child: Text('Go back'),
          ),
        ));
  }
}

您可以尝试使用以下代码

Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => YourNextScreen())),

I found a good tutorial that I have followed along, it is very comprehensive with screenshots and step by step, you can also download the code and just run it.我找到了一个很好的教程,我一直跟着,它非常全面,有截图和一步一步,你也可以下载代码并运行它。 Very helpful for me learning Flutter especially I am totally a begineer.对我学习 Flutter 非常有帮助,尤其是我完全是初学者。

https://medium.com/@misterflutter/lesson-5-creating-new-screens-f740994190c7 https://medium.com/@misterflutter/lesson-5-creating-new-screens-f740994190c7

https://medium.com/@misterflutter/lesson-6-creating-new-screens-part-2-4997085a43af?sk=d2a0fb723af42b78800f7cf19b312b62 https://medium.com/@misterflutter/lesson-6-creating-new-screens-part-2-4997085a43af?sk=d2a0fb723af42b78800f7cf19b312b62

使用新的Get 插件,您只需调用即可导航到新页面

Get.to(Page());

In formal method :

Navigator.push(context, MaterialPageRoute(builder: (context)=>Second()));

In GetX method :在 GetX 方法中:

Get.to(Second());

If we can navigate screen into another page and delete current page from stack then we can use method which is define below :如果我们可以将屏幕导航到另一个页面并从堆栈中删除当前页面,那么我们可以使用下面定义的方法:

Get.off(Third());

If we can navigate screen into another page and delete all route or page from stack then we can use the method which is define below :如果我们可以将屏幕导航到另一个页面并从堆栈中删除所有路由或页面,那么我们可以使用下面定义的方法:

Get.offAll(Third());

If we want to use Navigator.pop() then GetX give a Method which is define below :如果我们想使用 Navigator.pop() 那么 GetX 给出一个方法,定义如下:

Get.back();

Flutter has a similar implementation, using Navigator and Routes . Flutter 有一个类似的实现,使用NavigatorRoutes A Route is an abstraction for a “screen” or “page” of an app, and a Navigator is a widget that manages routes.路由是应用程序“屏幕”或“页面”的抽象,导航器是管理路由的小部件。

To navigate between pages, you have a couple of options:要在页面之间导航,您有几个选项:

  • Specify a Map of route names.指定路线名称的地图。
  • Directly navigate to a route.直接导航到路线。

The following example builds a Map.以下示例构建了一个 Map。

void main() {
  runApp(CupertinoApp(
    home: MyAppHome(), // becomes the route named '/'
    routes: <String, WidgetBuilder> {
      '/a': (BuildContext context) => MyPage(title: 'page A'),
      '/b': (BuildContext context) => MyPage(title: 'page B'),
      '/c': (BuildContext context) => MyPage(title: 'page C'),
    },
  ));
}

Navigate to a route by pushing its name to the Navigator.通过pushing其名称pushing送到导航器来导航到route

Navigator.of(context).pushNamed('/b');

The Navigator class handles routing in Flutter and is used to get a result back from a route that you have pushed on the stack. Navigator类处理 Flutter 中的路由,并用于从您推送到堆栈上的路由中获取返回结果。 This is done by awaiting the Future returned by push() .这是通过awaiting push()返回的Future来完成的。

For example, to start a 'location' route that lets the user select their location, you might do the following:例如,要开始一个让用户选择他们位置的“位置”路线,您可以执行以下操作:

Map coordinates = await Navigator.of(context).pushNamed('/location');

And then, inside your 'location' route, once the user has selected their location, pop() the stack with the result:然后,在您的“位置”路线中,一旦用户选择了他们的位置,就用结果pop()堆栈:

Navigator.of(context).pop({"lat":43.821757,"long":-79.226392});

您可以在构建小部件中使用这种方式

onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => NewScreen()));},

This way you can present the next screen这样您就可以呈现下一个屏幕

Navigator.of(context).push(
   MaterialPageRoute(fullscreenDialog: true,
   builder: (context) => const NewScreen(),
   ),
);
FloatingActionButton(
  onPressed: (){
    Navigator.of(context).push(MaterialPageRoute(builder: (context) => const AddUser()));
  },
  child: const Icon(Icons.add),
),

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

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