How do I display a notification badge when I receive a notification?

Asked

Viewed 151 times

-1

Hello, in my application I have a list that shows the users who sent messages. I want to place a notification badge when the user receives a notification. Any idea how I can get such a function? Follow my code:

class MessagesGet extends StatelessWidget {

  FirebaseUser _currentUser;

  DocumentSnapshot snapshot;

MessagesGet(this._currentUser, this.snapshot);

  Future<FirebaseUser> loadCurrentUser() async {
  if (_currentUser == null)
  _currentUser = await FirebaseAuth.instance.currentUser();
  if (_currentUser != null) {
  if (_currentUser == null) {

    await Firestore.instance.collection('users')
        .document(_currentUser.uid)
        .get();
         print(_currentUser.uid);
     }
   }
 }
 @override
 Widget build(BuildContext context) {
 return Container(
  child: StreamBuilder(
    stream: 

Firestore.instance.collection('chat').document(_currentUser.uid)
.collection('users').snapshots(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {

        return Center(
          child: CircularProgressIndicator(),
          );


      } else {
        return Scaffold(

          body: ListView.builder(
            padding: EdgeInsets.all(10.0),
            itemCount: snapshot.data.documents.length,
            itemBuilder: (context, index) {
              return MessagesScreen(snapshot.data.documents[index], _currentUser);
            },
          ),
        );
      }
    },
   ),
  );
 }
}


class MessagesScreen extends StatelessWidget {

 DocumentSnapshot snapshot;

 FirebaseUser _currentUser;

MessagesScreen(this.snapshot,this._currentUser);


@override
Widget build(BuildContext context) {
  return
      ListTile(
        contentPadding: EdgeInsets.only(top: 5.0, bottom: 5.0, left: 10.0),
        leading: CircleAvatar(
          radius: 25.0,
          backgroundColor: Colors.transparent,
          backgroundImage: NetworkImage(snapshot.data["photo"]),
        ),
        title: Text(
          snapshot.data["name"],
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        trailing: Padding(
          padding: const EdgeInsets.only(right: 10.0),
          child: Badge(),
        ),


        onTap: () {
          Navigator.of(context).push(MaterialPageRoute(
              builder: (context) => AdminChat(_currentUser, snapshot)));

        },
      );


 }
}

1 answer

0

Well, your example is not testable, which means that no one here will be able to run your code and see what is working or not working.

But taking into account that you want to present a badge of new notification, with a number or symbol above an icon, just use Stack together with Positioned:

Widget _buildNotificationIcon(int total) {
    return Stack(
      children: <Widget>[
        Icon(Icons.notifications),
        Positioned(
          top: 0.0,
          left: 0.0,
          child: Container(
            child: Padding(
              padding: const EdgeInsets.all(1.0),
              child: Center(
                child: Text(
                  '$total',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 10.0,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              color: Colors.orange,
            ),
            constraints: BoxConstraints(minWidth: 10),
          ),
        )
      ],
    );
  }

About when or not to show this icon will depend solely on your logic and how you manage your state. Test this code in practice with the dartpad.

It will produce that output:

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

Customize as you see fit. If your question referred to receiving push notification by firebase, it was not clear enough the problem, then you will have to follow the plugin documentation firebase_messaging.

  • Julio thanks for your attention, I didn’t put the whole code because it would be too big. In case I discovered a pluggin that already gives me the badge only declaring Child 'Badge", which is in the trailing of my Listtile. In case my question is how to trigger this badge to appear only when you have a new notification.

  • So, as I mentioned in my reply too, if you want such functionality you will have to implement push notification with the firebase_messaging plugin, the documentation contains a step by step. Or, an incorrect way, that would be to always consult your backend to show the notifications available.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.