Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading