WebView in Flutter : Adding TabBar, Step 2

We have been using webview in flutter to display web content on the screen. However, in our previous section we have just learned how to use webview in flutter.

Now we want to add some more style to our flutter app. As a result, we want to use the TabBar widget.

We use TabBar inside the AppBar in Flutter. 

When we select a tab, it displays a page. Just like the following screenshot.

WebView in Flutter _ adding TabBar to Flutter app
WebView in Flutter _ adding TabBar to Flutter app

As we see in the above image, we have placed each category on the TabBar. Consequently, when we click each category, it opens up the respective page.

For each page, we can use a different WebView widget. 

However, we couldn’t have done that if we didn’t use the TabBar.

Firstly, We’ve created tabs using the TabBar widget. Secondly, each page, or screen of any Flutter application should have a unique identity.

Finally, a TabBar needs a TabBarView widget to display different pages.

Besides using the TabBar, we have also decided to use the routes property of the MaterialApp widget.

All together we have five pages. The Home page and four pages that represent four categories. 

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_today/view/beginner.dart';
import 'package:flutter_today/view/dart_home.dart';
import 'package:flutter_today/view/flutter_apps.dart';
import 'package:flutter_today/view/intermediate.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../model/happy_theme.dart';
import '../controller/dashboard_home.dart';

HappyTheme happyTheme = HappyTheme();

class FlutterToday extends StatelessWidget {
  const FlutterToday({Key? key}) : super(key: key);

  /// This widget is the root of your application.
  /// this is third branch, we will add bottom navigation bar\
  /// in the next branch

  @override
  Widget build(BuildContext context) {
    final controller = Completer<WebViewController>();
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Today',
      theme: happyTheme.buildTheme(),
      initialRoute: '/',
      routes: {
        '/': (context) => const DashBoardHome(),
        Beginner.routeName: (context) => Beginner(
              webViewController: controller,
            ),
        Intermediate.routeName: (context) =>
            Intermediate(webViewController: controller),
        FlutterApps.routeName: (context) =>
            FlutterApps(webViewController: controller),
        DartHome.routeName: (context) =>
            DartHome(webViewController: controller),
      },
    );
  }
}

How to use TabBar inside WebView in Flutter

Our next goal is simple. 

We want to use the TabBar to display the categories on the Tabs so that users can select any tab to view all the posts.

When a tab is selected, the TabBar widget always looks up and tries to find the nearest DefaultTabController.

The DefaultTabController creates the TabController.

What is the function of the TabController?

Basically it maintains the synchronisation between tab and content.

That’s why, it asks how many tabs we’re going to create. The length property sets the value.

Let’s take a look at the Dash Board Home page. It will explain how we have used the TabBar and the TabController.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_today/view/beginner.dart';
import 'package:flutter_today/view/dart_home.dart';
import 'package:flutter_today/view/flutter_apps.dart';
import 'package:flutter_today/view/intermediate.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../view/home_page.dart';

class DashBoardHome extends StatefulWidget {
  const DashBoardHome({
    Key? key,
  }) : super(key: key);

  @override
  State<DashBoardHome> createState() => _DashBoardHomeState();
}

class _DashBoardHomeState extends State<DashBoardHome>
    with SingleTickerProviderStateMixin {
  final controller = Completer<WebViewController>();
  TabController? _tabController;

  final List<Tab> topTabs = <Tab>[
    const Tab(child: Text('HOME')),
    const Tab(child: Text('BEGINNERS')),
    const Tab(child: Text('INTERMEDIATE')),
    const Tab(child: Text('FLUTTER APPS')),
    const Tab(child: Text('DART')),
  ];

  @override
  void initState() {
    _tabController =
        TabController(length: topTabs.length, initialIndex: 0, vsync: this)
          ..addListener(() {
            setState(() {});
          });

    super.initState();
  }

  Future<bool> _onWillPop() async {
    if (_tabController?.index == 0) {
      await SystemNavigator.pop();
    }

    Future.delayed(const Duration(microseconds: 100), () {
      _tabController?.index = 0;
    });

    return _tabController?.index == 0;
  }

  final _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(5.0),
      child: WillPopScope(
        onWillPop: _onWillPop,
        child: Scaffold(
          key: _scaffoldKey,
          appBar: AppBar(
            title: Text(
              'FlutterToday',
              style: GoogleFonts.laila(
                fontSize: 35.0,
                fontWeight: FontWeight.bold,
                color: Colors.deepPurple,
              ),
            ),
            bottom: TabBar(
              controller: _tabController,
              indicatorColor: Colors.black,
              tabs: topTabs,
              isScrollable: true,
            ),
          ),
          body: TabBarView(
            controller: _tabController,
            children: [
              /// all categories displayed on tabs
              ///
              HomePage(webViewController: controller),
              Beginner(webViewController: controller),
              Intermediate(webViewController: controller),
              FlutterApps(webViewController: controller),
              DartHome(webViewController: controller),
            ],
          ),
        ),
      ),
    );
  }
}

The children property of the TabBar widget expects a list of pages that we will display on the tabs.

As an outcome, when we click each tab, it opens that page. 

If you want to clone this step, please visit this GitHub repository.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

One response to “WebView in Flutter : Adding TabBar, Step 2”

  1. […] In our previous section we have seen how we can use Flutter WebView widget with TabBar. […]

Leave a Reply