Home > Blockchain >  A value of type 'Null' can't be assigned to a parameter of type 'int'
A value of type 'Null' can't be assigned to a parameter of type 'int'

Time:02-17

I have the following code for HomePage class:

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  //inicializamos algunos valores

  late final FirebaseMessaging _messaging;
   late int totalNotificationCounter;
  PushNotification? _notificationInfo;

  //register Notification
  void registerNotification() async {

    await Firebase.initializeApp();
    //instance for Firebase Messaging
    _messaging = FirebaseMessaging.instance;

    //hay tres estados de los permisos para recibir la notificacion
    //not determined (null), granted (true), declined (false)

    NotificationSettings settings = await _messaging.requestPermission(
      alert: true,
      badge: true,
      provisional: false,
      sound: true
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized){
      print("User granted the permission");

      FirebaseMessaging.onMessage.listen((RemoteMessage message) {
        PushNotification notification = PushNotification(
          title: message.notification!.title,
          body: message.notification!.body,
          dataTitle: message.data['title'],
          dataBody: message.data['body']
        );

        setState(() {
          totalNotificationCounter   ;
          _notificationInfo = notification;
        });

      });
    }


  }
@override
  void initState() {
    // TODO: implement initState
    totalNotificationCounter = 0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("PushNotification"),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Text("Flutter Push Notification",textAlign: TextAlign.center,
            style: TextStyle(color: Colors.black,fontSize: 20),),
            //add notification badge to count total # of notifications received
            NotificationBadge(totalNotification: totalNotificationCounter),
          ],
        ),
      ),
    );
  }
}

And here the code for NotificationBadge class:

class NotificationBadge extends StatelessWidget {

   final int totalNotification;
  const NotificationBadge({Key? key,  required this.totalNotification}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 40,
        height: 40,
        decoration: const BoxDecoration(
          color: Colors.orange,
          shape: BoxShape.circle,
        ),
      child: Center(
        child: Padding(
          padding: EdgeInsets.all(8),
          child: Text("$totalNotification",style: TextStyle(color: Colors.white,fontSize: 20),),
        ),
      ),
    );
  }
}

There is an issue at line

NotificationBadge(totalNotification: totalNotificationCounter),

from the first class.

This is the error shown:

A value of type 'Null' can't be assigned to a parameter of type 'int' in a const constructor. (Documentation)  Try using a subtype, or removing the keyword 'const'.
Invalid constant value. 
The values in a const list literal must be constants. (Documentation)  Try removing the keyword 'const' from the list literal

I have tried removing the const from the seconde class, but other errors are shown.

CodePudding user response:

The cause of the issue is totalNotificationCounter not being initialized and totalNotification parameter needed in NotificationBadge() is non-nullable. You may want consider setting a default value to totalNotificationCounter and only display the Widget if the value is greater than 0.

i.e.

Column(
  children: [
    Text(),
    // Return empty Widget if totalNotificationCounter is 0
    totalNotificationCounter > 0 ? 
        NotificationBadge(totalNotification: totalNotificationCounter) : SizedBox(),
  ]
)

CodePudding user response:

in your initState add super.initState();

  @override
  void initState() {
    super.initState();
    totalNotificationCounter = 0;
  }
  • Related