Skip to content

Instantly share code, notes, and snippets.

@jorwan
Last active February 27, 2023 00:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorwan/53cd9ed07ad661f2577c43eaa7a6704e to your computer and use it in GitHub Desktop.
Save jorwan/53cd9ed07ad661f2577c43eaa7a6704e to your computer and use it in GitHub Desktop.
Flutter - Change between page with bottom navigation bar
/*
* Author: Jorge Wander Santana Urena
* Goal: Screen with page view & bottom pagination to change current page
**/
// Import material package to use UI
import 'package:flutter/material.dart';
main() => runApp(MyApp());
// Create statefull widget to use setState to repaint screen on change
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final int _pageAmount = 3;
// Create a page controller to change page programmatically
final _pageController = PageController(initialPage: 0);
int _selectedPage = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
// Init with a scaffold to set a bottom navigation bar
home: Scaffold(
// Set a PageView as a body to change between screen on page change
body: PageView(
// Disable user iteration to change page programmatically only
physics: NeverScrollableScrollPhysics(),
controller: _pageController,
// Repaint screen on page change
onPageChanged: (value) => setState(() => _selectedPage = value),
// Create pages
children: List<Scaffold>.generate(
_pageAmount, (index) => _createPage(title: 'Page ${index + 1}')),
),
// Create bottom navigation bar to change page
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedPage,
// Change page tap page number
onTap: (value) => _pageController.animateToPage(value,
duration: Duration(microseconds: 300), curve: Curves.easeIn),
// Create page numbers
items: List<BottomNavigationBarItem>.generate(_pageAmount,
(index) => _createBottomOption(title: '${index + 1}')),
),
),
);
}
_createBottomOption({String title}) => BottomNavigationBarItem(
label: title, icon: Icon(Icons.panorama_wide_angle));
_createPage({String title}) => Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(child: Text(title))
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment