Tab bar is a widely used widget when we make a mobile application.
It can help to navigation between pages.
Creating Pages
First, create pages to navigate.
// lib/tab_pages/first_page.dart
import 'package:flutter/material.dart';
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const Scaffold(body: Center(child: Text('This is a first page.')));
}
}
// lib/tab_pages/second_page.dart
import 'package:flutter/material.dart';
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const Scaffold(body: Center(child: Text('This is a second page.')));
}
}
I made two simple pages.
Using Tab Bar Widget
This is the most common part.
import 'package:flutter/material.dart';
import 'tab_pages/first_page.dart';
import 'tab_pages/second_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const TabBarApp(title: 'Tab Bar Example'),
);
}
}
class TabBarApp extends StatefulWidget {
const TabBarApp({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<TabBarApp> createState() => _TabBarApp();
}
I just imported two pages.
Now, let's take a look at the remaining part.
class _TabBarApp extends State<TabBarApp> with SingleTickerProviderStateMixin {
TabController? controller;
@override
void initState() {
super.initState();
controller = TabController(length: 2, vsync: this);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Tab Bar Example')),
body: TabBarView(
children: <Widget>[FirstPage(), SecondPage()],
controller: controller
),
bottomNavigationBar: TabBar(
tabs: const <Tab>[
Tab(icon: Icon(Icons.looks_one, color: Colors.blue)),
Tab(icon: Icon(Icons.looks_two, color: Colors.blue))
],
controller: controller
)
);
}
@override
void dispose() {
controller!.dispose();
super.dispose();
}
}
If we use the TabBar widget, we need TabController.
Therefore, I create a variable for TabController and initialize and dispose of it in the initState() and dispose().
And, configure the screen using build().
body property has TabBarView widget for viewing our pages and bottomNavigationBar property has TabBar widget to control page switching.
It wasn't difficult, was it?
'Dart (Flutter)' 카테고리의 다른 글
[Flutter] Save Data using Shared Preferences (0) | 2022.04.01 |
---|---|
[Flutter] Navigation (0) | 2022.03.30 |
[Flutter] Adding Fonts to Flutter Application (0) | 2022.03.26 |
[Flutter] Adding Image to Flutter Application (0) | 2022.03.26 |
[Flutter] Life Cycle (0) | 2022.03.23 |
댓글