はじめに
Flutter 3.7になり、Badge(バッヂ)のWidgetが追加されました。 それまでは独自で作ったり、サードパーティパッケージで実装してました。
クラス定義
クラス定義は下記のようになっています。
Badgeに表示する内容はlabel引数にWidgetで指定するようです。
その他、 ・背景色や文字色などの色指定 ・サイズ指定(labelを指定しなかった場合に適用される) などができるようになっています。
Badge Badge({ Key? key, Color? backgroundColor, Color? textColor, double? smallSize, double? largeSize, TextStyle? textStyle, EdgeInsetsGeometry? padding, AlignmentDirectional? alignment, Widget? label, bool isLabelVisible = true, Widget? child, })
実装
通常のバッヂ(labelのみ指定)
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'バッヂサンプル', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({Key? key}): super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('バッヂサンプル'), ), body: const Center( child: Badge( label: Text('1'), ), ), ); } }
アイコン上にバッヂ表示(labelとchild指定)
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'バッヂサンプル', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({Key? key}): super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('バッヂサンプル'), ), body: const Center( child: Badge( label: Text('1'), child: Icon(Icons.notifications) ), ), ); } }
最後に
詳しくは公式ドキュメントを参照