简体   繁体   English

Flutter - 收到通知时更改应用栏图标

[英]Flutter - change appbar icon when receiving notification

I am using FirebaseMessaging to push notifications on my app.我正在使用 FirebaseMessaging 在我的应用程序上推送通知。

So I can handle these notification with this code:所以我可以用这段代码处理这些通知:

firebaseMessaging.configure(
    onLaunch: (Map<String, dynamic> msg) {
  print("onLaunch called");
}, onResume: (Map<String, dynamic> msg) {
  print("onResume called");
}, onMessage: (Map<String, dynamic> msg) {
  print("onMessage called : " + msg.toString());
});

When I receive a notification, I want to display this little '1' on my icon in my appbar当我收到通知时,我想在我的应用栏中的图标上显示这个小“1”

图标

My problem is: I don't know how to change my bell icon dynamically on my appbar for all pages (and I can't call setState in my appbar)我的问题是:我不知道如何为所有页面在我的应用栏上动态更改我的铃铛图标(而且我无法在我的应用栏中调用 setState)

I think is pretty simple to solve your problem you only need to use a Stateful class and a custom icon as below snippet:我认为解决您的问题非常简单,您只需要使用有状态类和自定义图标,如下片段所示:

Widget myAppBarIcon(){
return Container(
  width: 30,
  height: 30,
  child: Stack(
    children: [
      Icon(
        Icons.notifications,
        color: Colors.black,
        size: 30,
      ),
      Container(
        width: 30,
        height: 30,
        alignment: Alignment.topRight,
        margin: EdgeInsets.only(top: 5),
        child: Container(
          width: 15,
          height: 15,
          decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Color(0xffc32c37),
              border: Border.all(color: Colors.white, width: 1)),
          child: Padding(
            padding: const EdgeInsets.all(0.0),
            child: Center(
              child: Text(
                _counter.toString(),
                style: TextStyle(fontSize: 10),
              ),
            ),
          ),
        ),
      ),
    ],
  ),
);
}

and later you can include this icon on your app bar(leading or action).稍后您可以将此图标包含在您的应用程序栏中(引导或操作)。 As you can see the Text value change with any touch I used as base the example code when you start a new Flutter project it contains a method to count how many times you touch the floating button and change the state:正如您所看到的,Text 值随着任何触摸而变化,我在开始一个新的 Flutter 项目时用作示例代码的基础,它包含一个方法来计算您触摸浮动按钮并更改状态的次数:

void _incrementCounter() {
setState(() {
  _counter++;
});
}

I hope this helps you我希望这可以帮助你

this is my example这是我的例子

Basic Idea behind the notification badge通知徽章背后的基本理念

Using Stack and Positioned widgets we can stack the Text widget over the IconButton to show the notification badge.使用 Stack 和 Positioned 小部件,我们可以将 Text 小部件堆叠在 IconButton 上以显示通知徽章。

appBar: AppBar(
        leading: IconButton(
          icon: Icon(
            _backIcon(),
            color: Colors.black,
          ),
          alignment: Alignment.centerLeft,
          tooltip: 'Back',
          onPressed: () {

          },
        ),
        title: Text(
          "Title",
          style: TextStyle(
            color: Colors.black,
          ),
        ),
        backgroundColor: Colors.white,
        actions: <Widget>[
          IconButton(
            tooltip: 'Search',
            icon: const Icon(
              Icons.search,
              color: Colors.black,
            ),
            onPressed: _toggle,
          ),
          new Padding(
            padding: const EdgeInsets.all(10.0),
            child: new Container(
              height: 150.0,
              width: 30.0,
              child: new GestureDetector(
                onTap: () {
                },
                child: Stack(
                  children: <Widget>[
                    new IconButton(
                        icon: new Icon(
                          Icons.shopping_cart,
                          color: Colors.black,
                        ),
                        onPressed: () {

                        }),
                    ItemCount == 0
                        ? new Container()
                        : new Positioned(
                            child: new Stack(
                            children: <Widget>[
                              new Icon(Icons.brightness_1,
                                  size: 20.0, color: Colors.orange.shade500),
                              new Positioned(
                                  top: 4.0,
                                  right: 5.0,
                                  child: new Center(
                                    child: new Text(
                                      ItemCount.toString(),
                                      style: new TextStyle(
                                          color: Colors.white,
                                          fontSize: 11.0,
                                          fontWeight: FontWeight.w500),
                                    ),
                                  )),
                            ],
                          )),
                  ],
                ),
              ),
            ),
          )
        ],
      ),

You have to create a custom drawable and set it as the Appbar icon and you have to paint the number as text in the custom drawable.您必须创建一个自定义可绘制对象并将其设置为 Appbar 图标,并且必须将数字绘制为自定义可绘制对象中的文本。 This is already done for you in the following link.这已经在以下链接中为您完成。

How to make an icon in the action bar with the number of notification?如何在操作栏中制作一个带有通知数量的图标?

you can just create variable of type IconData and change it's value.您可以只创建 IconData 类型的变量并更改它的值。 you will get more idea about that after gone through below example.在完成下面的示例后,您将对此有更多的了解。

import 'package:flutter/material.dart';导入“包:flutter/material.dart”;

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

class MyHome extends StatefulWidget {
  @override
  _MyHomeState createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {

  IconData _iconData= Icons.notifications;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Color(0xffFF5555),
      ),
      home: Scaffold(
        appBar: new AppBar(
          title: new Text("Title"),
          actions: <Widget>[
            Icon(_iconData)
          ],
        ),
        body: Center(
          child: new Text("Demo")
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.check_circle_outline),
            onPressed: (){
              if(_iconData == Icons.notifications){
                setState(() {
                  _iconData = Icons.notifications_active;
                });
              }else{
                setState(() {
                  _iconData = Icons.notifications;
                });
              }
            }
        ),
      ),
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM