首頁 > 軟體

Flutter自定義底部導航欄的方法

2022-07-28 22:04:49

本文範例為大家分享了Flutter自定義底部導航欄的具體程式碼,供大家參考,具體內容如下

檔案結構:

main.dart

import 'package:flutter/material.dart';
import 'pages/tabs.dart';
 
void main() => runApp(new MyApp());
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Tabs(),
    );
  }
}

tabs.dart

import 'package:flutter/material.dart';
import 'tabs/home.dart';
import 'tabs/category.dart';
import 'tabs/user.dart';
class Tabs extends StatefulWidget {
  Tabs({Key key}) : super(key: key);
  @override
  _TabsState createState() => _TabsState();
}
 
class _TabsState extends State<Tabs> {
  int _currentIndex = 0;
 
  List _pageList=[
    HomePage(),
    CategoryPage(),
    UserPage(),
  ];
 
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('自定義底部導航'),
      ),
      body: this._pageList[this._currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: this._currentIndex,
        onTap: (int index) {
          setState(() {
            this._currentIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('首頁'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.category),
            title: Text('分類'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.supervised_user_circle),
            title: Text('會員'),
          ),
        ],
      ),
    );
  }
}

home.dart

import 'package:flutter/material.dart';
 
class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);
 
  @override
  _HomePageState createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Text('首頁');
  }
}

category.dart

import 'package:flutter/material.dart';
 
class CategoryPage extends StatefulWidget {
  CategoryPage({Key key}) : super(key: key);
 
  @override
  _CategoryPageState createState() => _CategoryPageState();
}
 
class _CategoryPageState extends State<CategoryPage> {
  @override
  Widget build(BuildContext context) {
    return Text('分類');
  }
}

user.dart

import 'package:flutter/material.dart';
 
class UserPage extends StatefulWidget {
  UserPage({Key key}) : super(key: key);
 
  @override
  _UserPageState createState() => _UserPageState();
}
 
class _UserPageState extends State<UserPage> {
  @override
  Widget build(BuildContext context) {
    return Text('會員');
  }
}

效果展示:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com