flutter: 自定义BottomNavigationBarItem图标/文字大小位置

一,代码:

import 'package:flutter/material.dart';
import '../tabpages/MyHomePage.dart';
import '../tabpages/ProfilePage.dart';
import '../tabpages/WebviewPage.dart';

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

  @override
  State<MyTabBar> createState() => _MyTabBarState();
}

class _MyTabBarState extends State<MyTabBar> with SingleTickerProviderStateMixin {
  final List<Widget> pages = const [MyHomePage(), WebviewPage(),ProfilePage()];
  /// PageView 控制器 , 用于控制 PageView
  late PageController _pageController;
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(
      /// 初始索引值
      initialPage: 0,

    );
  }

  @override
  void dispose() {
    super.dispose();

    /// 销毁 PageView 控制器
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      /// 滑动组件 , 界面的核心元素
        body: PageView(
          /// 控制跳转翻页的控制器
          controller: _pageController,
          /// 页面滑动
          /// 这里设置 PageView 页面滑动也能
          onPageChanged: (index) {
            setState(() {
              // 更新当前的索引值
              _currentIndex = index;
            });
          },
          children: pages,
        ),
      bottomNavigationBar:Container(
        height: 105,
          decoration: const BoxDecoration(
            image: DecorationImage(
                image: AssetImage('images/b.png'),
                fit: BoxFit.fitWidth),
          ),
      child:SizedBox(height: 105, child:BottomNavigationBar(
        currentIndex: _currentIndex,
        selectedItemColor: Colors.red,
        //backgroundColor: Colors.transparent,
        //elevation: 0.0,
        onTap: (index) {
          setState(() {
            _pageController.animateToPage(
              index,
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
            _currentIndex = index;
          });
        },
        items: const [
          BottomNavigationBarItem(
            icon:Padding( // 使用Padding来调整图标位置
              padding: EdgeInsets.only(top: 36.0), // 向下移动图标
              child: Icon(Icons.home),
            ),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person,size:56),   //指定图标大小
            label: '发布',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.message),
            label: '消息',
          ),
        ],
        selectedLabelStyle: TextStyle(fontSize: 18), // 选中状态下的标签样式,包括字体大小
        unselectedLabelStyle: TextStyle(fontSize: 14), // 未选中状态下的标签样式,包括字体大小
      ),
      ),
      ),
    );
  }
}

 

二,测试效果:

 

posted @ 2025-04-12 08:47  刘宏缔的架构森林  阅读(124)  评论(0)    收藏  举报