0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Flutterで簡易コーポレートサイト(アプリ)を作成する #3 -タブバー編-

Last updated at Posted at 2023-03-13

概要

Top・Contactができたので、tabを設置してtabでTopとContactを行き来できるようにします。

完成イメージ

000001.jpg 000010.jpg

タブバー実装

top.dartとcontact.dartと同様の階層に「tab.dart」を作成します。

作成したtab.dartを下記のように記述します。

tab.dart
import 'package:flutter/material.dart';
import 'package:flutter_website/contact.dart';
import 'package:flutter_website/top.dart';

class TabWidget extends StatefulWidget {
  const TabWidget({super.key});

  @override
  State<TabWidget> createState() => _tabWidgetState();
}

class _tabWidgetState extends State<TabWidget> {
  int _selectedIndex = 0;

  static const List<Widget> _widgetOptions = <Widget>[TopPage(),ContactPage()];

  static const List<Widget> _titleOptions = <Widget>[Text("TOP"), Text("お問合せ")];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color.fromARGB(100, 0, 0, 0),
        title: _titleOptions.elementAt(_selectedIndex),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'TOP',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.info),
            label: 'お問合せ',
          ),
        ],
        currentIndex: _selectedIndex,
        onTap: _onItemTapped,
      ),
    );
  }
}

main.dart編集

main.dartでtabを表示するように編集します。

main.dart
  import 'package:flutter/material.dart';
+ import 'package:flutter_website/tab.dart';

- import 'top.dart';
- import 'contact.dart';

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

  class MyApp extends StatelessWidget {
    const MyApp({super.key});

    // This widget is the root of your application.
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Flutter Website',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
+       home: const TabWidget(),
-       home: const ContactPage(),
      );
    }
  }

確認

このようにタブバーで移動できるようになります。

000001.jpg 000010.jpg

関連コンテンツ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?