首页 > 解决方案 > Flutter - 收到通知时更改应用栏图标

问题描述

我正在使用 FirebaseMessaging 在我的应用程序上推送通知。

所以我可以用这段代码处理这些通知:

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());
});

当我收到通知时,我想在我的应用栏中的图标上显示这个小“1”

图标

我的问题是:我不知道如何在我的应用栏上为所有页面动态更改我的铃铛图标(而且我不能在我的应用栏中调用 setState)

标签: androiddartflutternotifications

解决方案


我认为解决您的问题非常简单,您只需要使用一个有状态的类和一个自定义图标,如下所示:

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),
              ),
            ),
          ),
        ),
      ),
    ],
  ),
);
}

稍后您可以在应用栏上包含此图标(引导或操作)。正如您所看到的,当您启动一个新的 Flutter 项目时,我用作示例代码的基础的任何触摸文本值都会发生变化,它包含一个方法来计算您触摸浮动按钮的次数并更改状态:

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

我希望这可以帮助你

这是我的例子


推荐阅读