flutter BottomNavigationBar底部导航栏大于三个的解决办法

1.使用方法

先看一下官网的例子:官方文档
可以看到官网的案例是底部导航是三个条目,可以正常显示
flutter BottomNavigationBar底部导航栏大于三个的解决办法_第1张图片

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int _selectedIndex = 0;
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static const List<Widget> _widgetOptions = <Widget>[
    Text(
      'Index 0: Home',
      style: optionStyle,
    ),
    Text(
      'Index 1: Business',
      style: optionStyle,
    ),
    Text(
      'Index 2: School',
      style: optionStyle,
    ),
    //这里多加了一个条目
    Text(
      'Index 3: Video',
      style: optionStyle,
    ),
  ];

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            title: Text('Business'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            title: Text('School'),
          ),
          //这里多加了一个条目
          BottomNavigationBarItem(
            icon: Icon(Icons.videocam),
            title: Text('Video'),
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

但是如果我们的导航大于三个时,显示就会出现一些问题,除了选中的条目,都会变成白色。
flutter BottomNavigationBar底部导航栏大于三个的解决办法_第2张图片
flutter BottomNavigationBar底部导航栏大于三个的解决办法_第3张图片

2.解决办法1:加selectedItemColor和unselectedItemColor

官网给的代码中已经有

selectedItemColor: Colors.amber[800],

我们再加上一行

unselectedItemColor: Colors.amber[800],

就可以得到下图的效果(当然颜色换成别的也可以)
flutter BottomNavigationBar底部导航栏大于三个的解决办法_第4张图片
但是这样的问题是无论unselectedItemColor我们用什么颜色,文字还是无法显示。

3.解决办法2: 使用type

直接加上一行

type: BottomNavigationBarType.fixed,

flutter BottomNavigationBar底部导航栏大于三个的解决办法_第5张图片
这回就可以正常显示了,解决了问题。

你可能感兴趣的:(flutter,前端)