Skip to content

[Flutter] How to navigate to another page and back

Last Updated on 2021-03-16 by Clay


Introduction

When we developing an App, sometimes we need many page to switch to do many different works. An App with only one page is relatively rare.

So, today I will record how to navigate another page.


Navigator

Let's take a look at a simple sample code.

import 'package:flutter/material.dart';

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


class Page01 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Page01'),
          ),
          body: _Page01()
      ),
    );
  }
}


class _Page01 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('Go to Page02'),
      onPressed: () {Navigator.push(context, MaterialPageRoute(builder: (context) => Page02()));},
    );
  }
}


class Page02 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page02'),
      ),
      body: _Page02(),
    );
  }
}


class _Page02 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Page02'),
    );
  }
}


Output:

Click the "Go to Page02" button.

And then we come to the Page02! now if you click the back button, you will return back to the Page01.

Of course, different pages can also be implemented in this way.


Code explanation

import 'package:flutter/material.dart';

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


To import the package or module you need, and set the entry point of our program.


class Page01 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Page01'),
          ),
          body: _Page01()
      ),
    );
  }
}
  • AppBar (You can pass it)
  • body: _Page01()

class _Page01 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('Go to Page02'),
      onPressed: () {Navigator.push(context, MaterialPageRoute(builder: (context) => Page02()));},
    );
  }
}


We define a button and write the page that Navigator will go to in onPress().


class Page02 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page02'),
      ),
      body: _Page02(),
    );
  }
}


We define Page02().


class _Page02 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Page02'),
    );
  }
}


_Page02() actually only defines a Text object, which is placed in the center of the screen and displays "Page02".


References


Read More

Tags:

Leave a Reply