Flutter PageView or Navigator

aadarshk7

Aadarsh Kunwar

Posted on August 17, 2024

Flutter PageView or Navigator

In Flutter, there are two common ways to navigate between pages or views: using the Navigator and implementing a page view with PageView.

  1. Using Navigator for Navigation Between Pages The Navigator is the primary way to manage a stack of routes, allowing you to push and pop routes (pages) to navigate between them.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home Page')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondPage()),
            );
          },
          child: Text('Go to Second Page'),
        ),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Page')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go back to Home Page'),
        ),
      ),
   );
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Using PageView for Swiping Between Pages PageView is useful for scenarios where you want to allow users to swipe between pages, similar to a carousel or a stepper.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PageViewExample(),
    );
  }
}

class PageViewExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('PageView Example')),
      body: PageView(
        children: <Widget>[
          Container(
            color: Colors.red,
            child: Center(child: Text('Page 1', style: TextStyle(fontSize: 24))),
          ),
          Container(
            color: Colors.green,
            child: Center(child: Text('Page 2', style: TextStyle(fontSize: 24))),
          ),
          Container(
            color: Colors.blue,
            child: Center(child: Text('Page 3', style: TextStyle(fontSize: 24))),
          ),
        ],
      ),
    );
  }
}

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
aadarshk7
Aadarsh Kunwar

Posted on August 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related