•  


Navigate to a new screen and back | Flutter

Navigate to a new screen and back

Most apps contain several screens for displaying different types of information. For example, an app might have a screen that displays products. When the user taps the image of a product, a new screen displays details about the product.

In Android, a route is equivalent to an Activity. In iOS, a route is equivalent to a ViewController. In Flutter, a route is just a widget.

This recipe uses the Navigator to navigate to a new route.

The next few sections show how to navigate between two routes, using these steps:

  1. Create two routes.
  2. Navigate to the second route using Navigator.push().
  3. Return to the first route using Navigator.pop().

1. Create two routes

#

First, create two routes to work with. Since this is a basic example, each route contains only a single button. Tapping the button on the first route navigates to the second route. Tapping the button on the second route returns to the first route.

First, set up the visual structure:

dart
class
 FirstRoute
 extends
 StatelessWidget
 {

  const
 FirstRoute
({
super
.key});


  @override

  Widget
 build
(
BuildContext
 context) {

    return
 Scaffold
(

      appBar: 
AppBar
(

        title: 
const
 Text
(
'First Route'
),

      ),

      body: 
Center
(

        child: 
ElevatedButton
(

          child: 
const
 Text
(
'Open route'
),

          onPressed: () {

            // Navigate to second route when tapped.

          },

        ),

      ),

    );

  }

}


class
 SecondRoute
 extends
 StatelessWidget
 {

  const
 SecondRoute
({
super
.key});


  @override

  Widget
 build
(
BuildContext
 context) {

    return
 Scaffold
(

      appBar: 
AppBar
(

        title: 
const
 Text
(
'Second Route'
),

      ),

      body: 
Center
(

        child: 
ElevatedButton
(

          onPressed: () {

            // Navigate back to first route when tapped.

          },

          child: 
const
 Text
(
'Go back!'
),

        ),

      ),

    );

  }

}

2. Navigate to the second route using Navigator.push()

#

To switch to a new route, use the Navigator.push() method. The push() method adds a Route to the stack of routes managed by the Navigator . Where does the Route come from? You can create your own, or use a MaterialPageRoute , which is useful because it transitions to the new route using a platform-specific animation.

In the build() method of the FirstRoute widget, update the onPressed() callback:

dart
// Within the `FirstRoute` widget

onPressed: () {

  Navigator
.
push
(

    context,

    MaterialPageRoute
(builder: (context) => 
const
 SecondRoute
()),

  );

}

3. Return to the first route using Navigator.pop()

#

How do you close the second route and return to the first? By using the Navigator.pop() method. The pop() method removes the current Route from the stack of routes managed by the Navigator .

To implement a return to the original route, update the onPressed() callback in the SecondRoute widget:

dart
// Within the SecondRoute widget

onPressed: () {

  Navigator
.
pop
(context);

}

Interactive example

#
import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    title: 'Navigation Basics',
    home: FirstRoute(),
  ));
}

class FirstRoute extends StatelessWidget {
  const FirstRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('First Route'),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text('Open route'),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const SecondRoute()),
            );
          },
        ),
      ),
    );
  }
}

class SecondRoute extends StatelessWidget {
  const SecondRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Second Route'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('Go back!'),
        ),
      ),
    );
  }
}
#

In the previous example you learned how to navigate between screens using the MaterialPageRoute from Material Components . However, in Flutter you are not limited to Material design language, instead, you also have access to Cupertino (iOS-style) widgets.

Implementing navigation with Cupertino widgets follows the same steps as when using MaterialPageRoute , but instead you use CupertinoPageRoute which provides an iOS-style transition animation.

In the following example, these widgets have been replaced:

This way, the example follows the current iOS design language.

import 'package:flutter/cupertino.dart';

void main() {
  runApp(const CupertinoApp(
    title: 'Navigation Basics',
    home: FirstRoute(),
  ));
}

class FirstRoute extends StatelessWidget {
  const FirstRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(
        middle: Text('First Route'),
      ),
      child: Center(
        child: CupertinoButton(
          child: const Text('Open route'),
          onPressed: () {
            Navigator.push(
              context,
              CupertinoPageRoute(builder: (context) => const SecondRoute()),
            );
          },
        ),
      ),
    );
  }
}

class SecondRoute extends StatelessWidget {
  const SecondRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(
        middle: Text('Second Route'),
      ),
      child: Center(
        child: CupertinoButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('Go back!'),
        ),
      ),
    );
  }
}
- "漢字路" 한글한자자동변환 서비스는 교육부 고전문헌국역지원사업의 지원으로 구축되었습니다.
- "漢字路" 한글한자자동변환 서비스는 전통문화연구회 "울산대학교한국어처리연구실 옥철영(IT융합전공)교수팀"에서 개발한 한글한자자동변환기를 바탕하여 지속적으로 공동 연구 개발하고 있는 서비스입니다.
- 현재 고유명사(인명, 지명등)을 비롯한 여러 변환오류가 있으며 이를 해결하고자 많은 연구 개발을 진행하고자 하고 있습니다. 이를 인지하시고 다른 곳에서 인용시 한자 변환 결과를 한번 더 검토하시고 사용해 주시기 바랍니다.
- 변환오류 및 건의,문의사항은 juntong@juntong.or.kr로 메일로 보내주시면 감사하겠습니다. .
Copyright ⓒ 2020 By '전통문화연구회(傳統文化硏究會)' All Rights reserved.
 한국   대만   중국   일본