Flutter 创建底部Tabbar与子控制器,去除底部点击动画效果

Flutter 创建底部Tabbar与子控制器,去除底部点击动画效果

1. 底部Tabbar的创建

底部tabbar的创建和实现使用的是BottomNavigationBar()函数来创建的,传入一个Items数组,里面存放的是BottomNavigationBarItem元素,类似于iOS,

  • BottomNavigationBar常见属性:
    • type:tabbar样式,默认为白色不显示;
    • fixedColor:tabbar选中颜色;
    • currentIndex:当前选中的Item的index
    • selectedFontSize:选中的title的size (默认14.0)
    • unselectedFontSize:未选中的title的size (默认12.0)
    • backgroundColor:背景色
    • iconSize:icon图片的size (默认是24.0)

type: BottomNavigationBarType.fixed,
fixedColor: Colors.greenAccent,
currentIndex: _cuttentIndex,

  • BottomNavigationBarItem常见的属性:
    • icon: 底部TabbarItem图片
    • title:底部TabbarItem标题
    • backgroundColor:背景色
      代码实现:

2 子控制器的创建

子控制器的实现原理是在Scaffold的body中,传入对应_currenIndex的控制器实例就;
rootpage中的代码如下:

class _RootPageState extends State<RootPage> {
  int _cuttentIndex = 0;
  List pages = [WeChatPage(),FriendsPage(),FindPage(),MinePage()];
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          fixedColor: Colors.greenAccent,
          currentIndex: _cuttentIndex,
          selectedFontSize: 12.0,
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(icon: Icon(Icons.chat), title: Text('微信')),
            BottomNavigationBarItem(
                icon: Icon(Icons.bookmark), title: Text('通讯录')),
            BottomNavigationBarItem(
                icon: Icon(Icons.history), title: Text('发现')),
            BottomNavigationBarItem(
                icon: Icon(Icons.person_outline), title: Text('我的')),
          ],
          onTap: (int index) {
            _cuttentIndex = index;
            print('index = $index');
            setState(() {}); //刷新状态
          },
        ),
        body: pages[_cuttentIndex],//传入数据源数组中对应index的控制器即可
      ),
    );
  }
}

子控制器需要返回一个有状态的Scaffold,创建不同的Appbar即可,代码如下:

import 'package:flutter/material.dart';

class WeChatPage extends StatefulWidget {
  @override
  _WeChatPageState createState() => _WeChatPageState();
}

class _WeChatPageState extends State<WeChatPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('微信'),
        ),
        body: Center(
          child: Text('Wechat'),
        ));
  }
}

运行效果

3 去除底部Item点击默认的波纹效果

在点击底部的Item时,会出现一个选中的波纹动画效果,这实际上是MaterialApp的一个属性设置,我们可以将这个属性的色值改成透明色即可,代码如下:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'WeChat',
      theme: ThemeData(
          primaryColor: Colors.greenAccent,
          highlightColor: Color.fromRGBO(0, 0, 0, 0),
          splashColor: Color.fromRGBO(0, 0, 0, 0)),
      home: RootPage(),
    );
  }
}

发布了8 篇原创文章 · 获赞 0 · 访问量 469

猜你喜欢

转载自blog.csdn.net/wyyrls/article/details/104045682