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

Tho*_*ole 2 notifications android dart 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());
});
Run Code Online (Sandbox Code Playgroud)

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

图标

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

小智 5

我认为解决您的问题非常简单,您只需要使用Stateful类和自定义图标即可:

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),
              ),
            ),
          ),
        ),
      ),
    ],
  ),
);
Run Code Online (Sandbox Code Playgroud)

}

然后您可以在应用程序栏上添加此图标(领导或操作)。正如您所看到的,当您启动新的Flutter项目时,我以示例代码为基础的任何触摸都会改变Text值,它包含一种计算触摸浮动按钮并更改状态的次数的方法:

void _incrementCounter() {
setState(() {
  _counter++;
});
Run Code Online (Sandbox Code Playgroud)

}

我希望这可以帮助你

这是我的例子