📜  Flutter – 实现徽章

📅  最后修改于: 2022-05-13 01:55:20.219000             🧑  作者: Mango

Flutter – 实现徽章

徽章可用于应用程序中的各种目的。例如,显示消息的数量、购物车中的商品数量等。在本文中,我们将看到使用徽章Flutter包在Flutter中实现徽章。

安装库:

pubspec.yaml文件中,添加徽章库。然后运行 pub get 来配置依赖。

或者只需在 IDE 的终端中运行以下命令:

flutter pub add badges

导入库:

主要。 dart将其导入为:

Dart
import 'package:badges/badges.dart';


Dart
Badge(
              badgeContent: Text(
                '5',
                style: TextStyle(color: Colors.white, fontSize: 30),
              ),
              badgeColor: Colors.green,
              child: Icon(Icons.person, size: 50),
            ),
  
Badge(
              elevation: 0,
              position: BadgePosition.topEnd(),
              padding: EdgeInsetsDirectional.only(end: 0),
              badgeColor: Colors.transparent,
              badgeContent: Icon(Icons.error, size: 27.0, color: Colors.red),
              child: Text(
                'This is RTL',
                style: TextStyle(fontSize: 30),
              ),
            ),


Dart
int _counter = 0;


Dart
Badge(
          position: BadgePosition.topEnd(top: 0, end: 3),
          animationDuration: Duration(milliseconds: 300),
          animationType: BadgeAnimationType.slide,
          badgeContent: Text(
            _counter.toString(),
            style: TextStyle(color: Colors.white),
          ),
          child: IconButton(
              icon: Icon(Icons.shopping_cart),
              onPressed: () {
                print("These are items in your cart");
              }),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton.icon(
                  onPressed: () {
                    setState(() {
                      _counter++;
                    });
                  },
                  icon: Icon(Icons.add),
                  label: Text('Add Items')),
              ElevatedButton.icon(
                  onPressed: () {
                    if (_counter > 0) {
                      setState(() {
                        _counter--;
                      });
                    }
                  },
                  icon: Icon(Icons.remove),
                  label: Text('Remove Items')),
            ],
          ),
        ),


Dart
Badge(
              padding: EdgeInsets.all(6),
              gradient: LinearGradient(colors: [
                Colors.red,
                Colors.green,
              ]),
              badgeContent: Text(
                '!',
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 20,
                ),
              ),
              shape: BadgeShape.square,
              borderRadius: BorderRadius.circular(10),
              toAnimate: true,
              animationType: BadgeAnimationType.scale,
              animationDuration: Duration(seconds: 2),
              position: BadgePosition.topStart(top: -15, start: 80),
              child: Center(
                child: Text(
                  'This is a text',
                  style: TextStyle(fontSize: 30),
                ),
              ),
            )


Dart
Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Chip(
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  labelPadding: EdgeInsets.all(20),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  avatar: Icon(Icons.delete, color: Colors.white),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  labelStyle: TextStyle(fontSize: 20, letterSpacing: 4),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
            ],
          )


Dart
import 'package:badges/badges.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.green),
      home: HomeScreen(),
    );
  }
}
  
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}
  
class _HomeScreenState extends State {
  int _counter = 0;
  bool showElevatedButtonBadge = true;
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Badge(
          position: BadgePosition.topEnd(top: 10, end: 10),
          badgeContent: null,
          child: IconButton(
            icon: const Icon(Icons.menu),
            onPressed: () {},
          ),
        ),
        title:
            const Text('GeeksForGeeks', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.green,
        centerTitle: true,
      ),
      body: Column(
        children: [
          SizedBox(
            height: 100,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Chip(
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  labelPadding: EdgeInsets.all(20),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  avatar: Icon(Icons.delete, color: Colors.white),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  labelStyle: TextStyle(fontSize: 20, letterSpacing: 4),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
            ],
          ),
          ListTile(
            trailing: Padding(
              padding: const EdgeInsets.only(left: 20),
              child: Icon(
                Icons.arrow_forward_ios,
                size: 14,
                color: Colors.black,
              ),
            ),
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("Messages"),
                Badge(
                  elevation: 0,
                  shape: BadgeShape.circle,
                  padding: EdgeInsets.all(7),
                  badgeContent: Text(
                    "2",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ],
            ),
          ),
          Badge(
            position: BadgePosition.topEnd(top: 0, end: 3),
            animationDuration: Duration(milliseconds: 300),
            animationType: BadgeAnimationType.slide,
            badgeContent: Text(
              _counter.toString(),
              style: TextStyle(color: Colors.white),
            ),
            child: IconButton(
                icon: Icon(Icons.shopping_cart),
                onPressed: () {
                  print("These are items in your cart");
                }),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton.icon(
                    onPressed: () {
                      setState(() {
                        _counter++;
                      });
                    },
                    icon: Icon(Icons.add),
                    label: Text('Add Items')),
                ElevatedButton.icon(
                    onPressed: () {
                      if (_counter > 0) {
                        setState(() {
                          _counter--;
                        });
                      }
                    },
                    icon: Icon(Icons.remove),
                    label: Text('Remove Items')),
              ],
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Badge(
            badgeContent: Text(
              '5',
              style: TextStyle(color: Colors.white, fontSize: 30),
            ),
            badgeColor: Colors.green,
            child: Icon(Icons.person, size: 50),
          ),
          SizedBox(
            height: 50,
          ),
          Center(
            child: Badge(
              elevation: 0,
              position: BadgePosition.topEnd(),
              padding: EdgeInsetsDirectional.only(end: 0),
              badgeColor: Colors.transparent,
              badgeContent: Icon(Icons.error, size: 27.0, color: Colors.red),
              child: Text(
                'This is RTL',
                style: TextStyle(fontSize: 30),
              ),
            ),
          ),
        ],
      ),
    );
  }
}


执行:

可以使用Badge() 小部件创建徽章。它包括几个属性——badgeContentbadgeColorchildposition等。在下面的例子中,我们创建了两个简单的徽章。

Dart

Badge(
              badgeContent: Text(
                '5',
                style: TextStyle(color: Colors.white, fontSize: 30),
              ),
              badgeColor: Colors.green,
              child: Icon(Icons.person, size: 50),
            ),
  
Badge(
              elevation: 0,
              position: BadgePosition.topEnd(),
              padding: EdgeInsetsDirectional.only(end: 0),
              badgeColor: Colors.transparent,
              badgeContent: Icon(Icons.error, size: 27.0, color: Colors.red),
              child: Text(
                'This is RTL',
                style: TextStyle(fontSize: 30),
              ),
            ),

输出:

现在,让我们再举一个例子,我们将在其中创建一个购物车图标,并向其中添加和删除项目。在类中初始化_counter以显示购物车中物品的增量和减量。

Dart

int _counter = 0;

然后我们创建两个ElevatedButton.icon()一个用于将商品添加到购物车,另一个用于删除商品。每次按下这些按钮时,我们使用setState()方法设置新状态。现在我们使用 Badge() 小部件并创建一个购物车图标作为其子级,使用 position 属性将徽章定位在其顶部。我们还使用 BadgeAnimationType 为其添加了幻灯片动画。我们将 _counter 值作为字符串传递给badgeContent属性。

Dart

Badge(
          position: BadgePosition.topEnd(top: 0, end: 3),
          animationDuration: Duration(milliseconds: 300),
          animationType: BadgeAnimationType.slide,
          badgeContent: Text(
            _counter.toString(),
            style: TextStyle(color: Colors.white),
          ),
          child: IconButton(
              icon: Icon(Icons.shopping_cart),
              onPressed: () {
                print("These are items in your cart");
              }),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton.icon(
                  onPressed: () {
                    setState(() {
                      _counter++;
                    });
                  },
                  icon: Icon(Icons.add),
                  label: Text('Add Items')),
              ElevatedButton.icon(
                  onPressed: () {
                    if (_counter > 0) {
                      setState(() {
                        _counter--;
                      });
                    }
                  },
                  icon: Icon(Icons.remove),
                  label: Text('Remove Items')),
            ],
          ),
        ),

输出:

带方向的方形徽章:

我们还可以自定义徽章的形状。在下面的示例中,我们正在创建一个带有渐变颜色的方形徽章,并为其添加动画以及持续时间。

Dart

Badge(
              padding: EdgeInsets.all(6),
              gradient: LinearGradient(colors: [
                Colors.red,
                Colors.green,
              ]),
              badgeContent: Text(
                '!',
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 20,
                ),
              ),
              shape: BadgeShape.square,
              borderRadius: BorderRadius.circular(10),
              toAnimate: true,
              animationType: BadgeAnimationType.scale,
              animationDuration: Duration(seconds: 2),
              position: BadgePosition.topStart(top: -15, start: 80),
              child: Center(
                child: Text(
                  'This is a text',
                  style: TextStyle(fontSize: 30),
                ),
              ),
            )

输出:

使用徽章的筹码:

我们还可以使用徽章库创建芯片。但是我们需要使用Chip()小部件。它包括属性 - labellabelStyle等。我们可以根据我们的要求对其进行自定义。例如,我们可以给它形状、背景颜色、头像等。请参阅下面的示例以获得更多理解。

Dart

Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Chip(
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  labelPadding: EdgeInsets.all(20),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  avatar: Icon(Icons.delete, color: Colors.white),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  labelStyle: TextStyle(fontSize: 20, letterSpacing: 4),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
            ],
          )

输出:

完整的源代码:

Dart

import 'package:badges/badges.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.green),
      home: HomeScreen(),
    );
  }
}
  
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}
  
class _HomeScreenState extends State {
  int _counter = 0;
  bool showElevatedButtonBadge = true;
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Badge(
          position: BadgePosition.topEnd(top: 10, end: 10),
          badgeContent: null,
          child: IconButton(
            icon: const Icon(Icons.menu),
            onPressed: () {},
          ),
        ),
        title:
            const Text('GeeksForGeeks', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.green,
        centerTitle: true,
      ),
      body: Column(
        children: [
          SizedBox(
            height: 100,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Chip(
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  labelPadding: EdgeInsets.all(20),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  avatar: Icon(Icons.delete, color: Colors.white),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
              Chip(
                  labelStyle: TextStyle(fontSize: 20, letterSpacing: 4),
                  label: Text(
                    'Hello',
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(0),
                  backgroundColor: Colors.blue),
            ],
          ),
          ListTile(
            trailing: Padding(
              padding: const EdgeInsets.only(left: 20),
              child: Icon(
                Icons.arrow_forward_ios,
                size: 14,
                color: Colors.black,
              ),
            ),
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("Messages"),
                Badge(
                  elevation: 0,
                  shape: BadgeShape.circle,
                  padding: EdgeInsets.all(7),
                  badgeContent: Text(
                    "2",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ],
            ),
          ),
          Badge(
            position: BadgePosition.topEnd(top: 0, end: 3),
            animationDuration: Duration(milliseconds: 300),
            animationType: BadgeAnimationType.slide,
            badgeContent: Text(
              _counter.toString(),
              style: TextStyle(color: Colors.white),
            ),
            child: IconButton(
                icon: Icon(Icons.shopping_cart),
                onPressed: () {
                  print("These are items in your cart");
                }),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton.icon(
                    onPressed: () {
                      setState(() {
                        _counter++;
                      });
                    },
                    icon: Icon(Icons.add),
                    label: Text('Add Items')),
                ElevatedButton.icon(
                    onPressed: () {
                      if (_counter > 0) {
                        setState(() {
                          _counter--;
                        });
                      }
                    },
                    icon: Icon(Icons.remove),
                    label: Text('Remove Items')),
              ],
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Badge(
            badgeContent: Text(
              '5',
              style: TextStyle(color: Colors.white, fontSize: 30),
            ),
            badgeColor: Colors.green,
            child: Icon(Icons.person, size: 50),
          ),
          SizedBox(
            height: 50,
          ),
          Center(
            child: Badge(
              elevation: 0,
              position: BadgePosition.topEnd(),
              padding: EdgeInsetsDirectional.only(end: 0),
              badgeColor: Colors.transparent,
              badgeContent: Icon(Icons.error, size: 27.0, color: Colors.red),
              child: Text(
                'This is RTL',
                style: TextStyle(fontSize: 30),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

输出: