Flutter底部导航栏带徽章插件bottom_navigation_badge的使用

BottomNavigationBadge 是一个由 westdabestdb 开发的 Flutter 类库,用于在底部导航栏中添加徽章(Badge)。通过该插件,您可以轻松为底部导航栏的每个选项卡添加带有文本或图标的徽章。

安装插件

首先,在您的项目中添加依赖项。打开项目的 pubspec.yaml 文件,并添加以下内容:

dependencies:
  bottom_navigation_badge: ^1.0.3

然后运行以下命令以安装依赖项:

flutter pub get

接下来,在 Dart 文件中导入插件:

import 'package:bottom_navigation_badge/bottom_navigation_badge.dart';

使用示例

以下是一个完整的示例,展示如何使用 bottom_navigation_badge 插件来为底部导航栏添加徽章。

import 'package:flutter/material.dart';
import 'package:bottom_navigation_badge/bottom_navigation_badge.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 初始化徽章生成器
  BottomNavigationBadge badger = BottomNavigationBadge(
    backgroundColor: Colors.red, // 徽章背景颜色
    badgeShape: BottomNavigationBadgeShape.circle, // 徽章形状(圆形)
    textColor: Colors.white, // 文本颜色
    position: BottomNavigationBadgePosition.topRight, // 徽章位置(右上角)
    textSize: 8, // 文本大小
  );

  // 底部导航栏的选项列表
  List<BottomNavigationBarItem> items = [
    BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("Home")),
    BottomNavigationBarItem(icon: Icon(Icons.notifications), title: Text("Notifications")),
    BottomNavigationBarItem(icon: Icon(Icons.face), title: Text("Profile")),
  ];

  // 当前选中的导航栏索引
  int _current = 0;

  // 添加徽章的方法
  void _addBadge(String content, int index) {
    setState(() {
      items = badger.setBadge(items, content, index); // 在指定索引处添加徽章
    });
  }

  // 移除指定索引的徽章
  void _removeBadge(int index) {
    setState(() {
      items = badger.removeBadge(items, index); // 移除指定索引的徽章
    });
  }

  // 移除所有徽章
  void _removeAllBadges() {
    setState(() {
      items = badger.removeAll(items); // 移除所有徽章
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("底部导航栏带徽章示例"),
        backgroundColor: Colors.black,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 选择导航项
            Row(
              children: [
                Text("导航项: "),
                DropdownButton<int>(
                  value: items.indexWhere((item) => item == items[_current]),
                  items: items.map((item) {
                    return DropdownMenuItem<int>(
                      value: items.indexOf(item),
                      child: item.title,
                    );
                  }).toList(),
                  onChanged: (value) {
                    setState(() {
                      _current = value!;
                    });
                  },
                ),
              ],
            ),
            // 输入徽章内容
            Row(
              children: [
                Text("徽章内容: "),
                Expanded(
                  child: TextField(
                    decoration: InputDecoration(hintText: "输入徽章内容"),
                    controller: TextEditingController(),
                  ),
                ),
              ],
            ),
            // 按钮操作区域
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () {
                    // 获取用户输入的徽章内容
                    final content = TextEditingController().text;
                    if (content.isNotEmpty) {
                      _addBadge(content, items.indexOf(items[_current]));
                    }
                  },
                  child: Text("添加徽章"),
                ),
                ElevatedButton(
                  onPressed: () {
                    // 移除当前选中的导航项的徽章
                    _removeBadge(items.indexOf(items[_current]));
                  },
                  child: Text("移除徽章"),
                ),
                ElevatedButton(
                  onPressed: () {
                    // 移除所有导航项的徽章
                    _removeAllBadges();
                  },
                  child: Text("移除所有徽章"),
                ),
              ],
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _current,
        onTap: (index) {
          setState(() {
            _current = index;
          });
        },
        items: items,
      ),
    );
  }
}

更多关于Flutter底部导航栏带徽章插件bottom_navigation_badge的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter底部导航栏带徽章插件bottom_navigation_badge的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中,bottom_navigation_badge 是一个用于在底部导航栏中添加徽章(Badge)的插件。它可以方便地在底部导航栏的图标上显示数字或文字,用于提示未读消息、通知等。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 bottom_navigation_badge 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  bottom_navigation_badge: ^1.0.0

然后运行 flutter pub get 来获取依赖。

2. 基本使用

以下是一个简单的示例,展示如何使用 bottom_navigation_badge 插件在底部导航栏中添加徽章。

import 'package:flutter/material.dart';
import 'package:bottom_navigation_badge/bottom_navigation_badge.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BottomNavigationBadgeExample(),
    );
  }
}

class BottomNavigationBadgeExample extends StatefulWidget {
  @override
  _BottomNavigationBadgeExampleState createState() =>
      _BottomNavigationBadgeExampleState();
}

class _BottomNavigationBadgeExampleState
    extends State<BottomNavigationBadgeExample> {
  int _selectedIndex = 0;

  // 定义徽章数据
  final List<Badge> _badges = [
    Badge(text: '3', color: Colors.red), // 第一个图标显示红色徽章,内容为 '3'
    Badge(text: 'New', color: Colors.green), // 第二个图标显示绿色徽章,内容为 'New'
    Badge(), // 第三个图标没有徽章
  ];

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bottom Navigation with Badge'),
      ),
      body: Center(
        child: Text('Selected Index: $_selectedIndex'),
      ),
      bottomNavigationBar: BottomNavigationBadge(
        currentIndex: _selectedIndex,
        onTap: _onItemTapped,
        items: [
          BottomNavigationBadgeItem(
            icon: Icon(Icons.home),
            badge: _badges[0],
          ),
          BottomNavigationBadgeItem(
            icon: Icon(Icons.business),
            badge: _badges[1],
          ),
          BottomNavigationBadgeItem(
            icon: Icon(Icons.school),
            badge: _badges[2],
          ),
        ],
      ),
    );
  }
}

3. 代码解释

  • Badge: Badge 类用于定义徽章的内容和颜色。你可以通过 text 属性设置徽章显示的文本,通过 color 属性设置徽章的颜色。
  • BottomNavigationBadgeItem: BottomNavigationBadgeItem 类用于定义底部导航栏的每个项目。你可以通过 icon 属性设置图标,通过 badge 属性设置徽章。
  • BottomNavigationBadge: BottomNavigationBadge 是底部导航栏的包装器,它接受 items 参数来定义导航栏的各个项目,并通过 currentIndexonTap 来管理当前选中的索引和点击事件。

4. 自定义徽章

你可以通过 Badge 类的属性来自定义徽章的外观,例如:

  • text: 徽章显示的文本。
  • color: 徽章的背景颜色。
  • textColor: 徽章文本的颜色。
  • shape: 徽章的形状(圆形或矩形)。

5. 动态更新徽章

你可以通过更新 _badges 列表中的数据来动态更新徽章的内容。例如:

void _updateBadge(int index, String text) {
  setState(() {
    _badges[index] = Badge(text: text, color: Colors.blue);
  });
}
回到顶部