How to make optional datetime parameter in flutter dart with null safety

Issue

I’m new to Flutter darts development and trying to learn.
I want to create a model with a constructor, one of which contains a field of type DateTime which is optional.

I tried by making it like this:

import 'package:equatable/equatable.dart';

class Customer extends Equatable {
  final int indexs;
  final DateTime apply_date;

  Customer({
    required this.indexs,
    this.apply_date,
  });

  @override
  List<Object?> get props => throw UnimplementedError();
}

But an error message appears like this

The parameter ‘apply_date’ can’t have a value of ‘null’ because of its
type, but the implicit default value is ‘null’. Try adding either an
explicit non-‘null’ default value or the ‘required’ modifier.

I’ve tried to learn from this and this reference, and what I understand there are 3 ways:

  1. Include required modifiers
  2. Set initial value
  3. Nulllabel parameter / Fill it with (?) => I don’t understand this

So how to do this properly?
I don’t want to make this field required, because it’s optional.
I also don’t know what to fill if I want to fill it with an initialvalue..

Thank you

Solution

Making the attribute nullable is the same as making it an optional attribute.

You can do that by adding ? behind the attribute’s type.

class Customer extends Equatable {
  final int indexs;
  final DateTime? apply_date;

  Customer({
    required this.indexs,
    this.apply_date,
  });

  @override
  List<Object?> get props => throw UnimplementedError();
}

Answered By – jazzsim

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *