[Flutter]How to Go Back and Forth Pages?? (Day 10)

Flutter

Introduction

Hi guys!!

I’m Craze😎

Don’t you ever have those moments when you are doing something on your phone and you are like “Oh no, I messed up“, or “Let me go back to the previous page“?

That happens to me quite a lot😭

Thus, today I learned about the Navigator method

I’ve studied implementing a PageView method in the previous blog post

It seems the same thing as the Navigator, but technically they have different purposes

These are the differences between them

FeatureNavigatorPageView
PurposeNavigate between independent screens.Swipeable interface for pages.
StructureUses a stack-based navigation model.Part of the same widget tree.
StateState is independent between routes.State is shared (or can be).
InteractionPush/Pop for navigation.Swipe gestures to move between.
Use CaseIndependent screens like Home, Login.Carousels, onboarding, tabs.

After understanding these two, I realised that I should’ve used the Navigator instead of the PageView when I created the setup screen.

Anyway, Let’s have a look at what its code looks like😄

Sample Code

This widget can be used when your app needs independent screens or routes that are navigated sequentially or hierarchically.

Navigator.push: To add a new route / To navigate to a new screen

Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => NextScreen(), // Replace with your next screen
  ),
);

Navigator.pop: To remove the current route / To go back to the previous screen

result is optional and allows you to pass data back to the previous screen.

Navigator.pop(context, result);

Example Code

This is the final form of the example code

first_screen.dart

import 'package:flutter/material.dart';
import 'package:flutter_navigagtorpop/second_screen.dart';

class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  String result = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('First Screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Result: ${result}'),
            ElevatedButton(
              onPressed: () async {
                // Wait for the result from SecondScreen
                final result = await Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => SecondScreen()),
                );
                setState(() {
                  this.result = result;
                });
              },
              child: Text('Go to Second Screen'),
            ),
          ],
        ),
      ),
    );
  }
}

second_screen.dart

import 'package:flutter/material.dart';

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Screen')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Return data to FirstScreen
            Navigator.pop(context, 'Hello from Second Screen!');
          },
          child: Text('Go Back with Data'),
        ),
      ),
    );
  }
}

Conclusion

How do you feel about the Navigator widget?

It’s so useful and straightforward, isn’t it?

Thank you for reading, guys😄

コメント

タイトルとURLをコピーしました