skip to Main Content

enter image description here

In this class I dont want to (chatCard.person) named constructor has subtitle property.Because I dont need it.But as you can see I have this error :All final variables must be initialized, but ‘subtitle’ isn’t.
Try adding an initializer for the field.
I know that If I remove final keyWord from its definition in third line the error will remove But then the class isnt immutable.
So any idea?

2

Answers


  1. You can use a factory constructor that doesn’t include the subtitle property:

    class ChatCard extends StatelessWidget {
      const ChatCard._({
        this.title,
        this.subtitle,
        this.lastSeenTime,
        this.lastMessageTime,
        this.pic,
        this.unSeenMessageNumber,
        this.memberSubscribeNumber,
        this.isOnline,
        this.seenStatus,
      });
    
      factory ChatCard.person({
        required String? title,
        required String? lastSeenTime,
        required String? lastMessageTime,
        required String? pic,
        required String? unSeenMessageNumber,
        required String? memberSubscribeNumber,
        required bool? isOnline,
        required bool? seenStatus,
      }) =>
          ChatCard._(
            title: title,
            lastSeenTime: lastSeenTime,
            lastMessageTime: lastMessageTime,
            pic: pic,
            unSeenMessageNumber: unSeenMessageNumber,
            memberSubscribeNumber: memberSubscribeNumber,
            isOnline: isOnline,
            seenStatus: seenStatus,
          );
    
      final String? title;
      final String? subtitle;
      final String? lastSeenTime;
      final String? lastMessageTime;
      final String? pic;
      final String? unSeenMessageNumber;
      final String? memberSubscribeNumber;
      final bool? isOnline;
      final bool? seenStatus;
    
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        throw UnimplementedError();
      }
    }
    
    Login or Signup to reply.
  2. You can follow like

      const ChatCard.person({
        super.key,
         .....
      }) : subtitle = null;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search