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 BottomNavigationBarでonTapを実装し表示切り替え

Posted at

BottomNavigationBarItemを3つ作成し、各アイコンをタップすると対象のWidgetを表示するようにコーディングしてみる。

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _selectedIndex = 0;
  
  static const _pages =[
    Scaffold(body: Center(child: Text('Home'))),
    Scaffold(body: Center(child: Text('Article'))),
    Scaffold(body: Center(child: Text('Settings'))),
  ];

  void _onTap(final int index){
    setState((){
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('MyApp'),),
        body: _pages[_selectedIndex],
        bottomNavigationBar: BottomNavigationBar(
          items: const [
            BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home',),
            BottomNavigationBarItem(icon: Icon(Icons.article), label: 'Article',),
            BottomNavigationBarItem(icon: Icon(Icons.settings_accessibility), label: 'Settings',),
          ],
          currentIndex: _selectedIndex,
          onTap: _onTap,
        ),
      ),
    );
  }
}

結果

下のアイコンをタップする都度、対象の文字列が表示されWidgetが切り替わっていることを確認できた。
スクリーンショット 2023-10-11 0.20.27.png

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?