0

I am trying to wrap a Visibility widget through a TextFormField and found this error:

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building UserPage(dirty, dependencies: [_LocalizationsScope-[GlobalKey#f23fa], _InheritedTheme], state: _UserPageState#df216):
The getter 'microsecondsSinceEpoch' was called on null.
Receiver: null
Tried calling: microsecondsSinceEpoch

The relevant error-causing widget was: 
  UserPage file:///Users/mahmoudalharoon/Desktop/InterViewProjects/Mobile%20Technologies/mttest/lib/page/home_page.dart:44:37
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      DateTime.difference (dart:core-patch/date_patch.dart:201:54)
#2      _UserPageState.buildUsers (package:mttest/page/user_page.dart:161:33)
#3      _UserPageState.build (package:mttest/page/user_page.dart:46:15)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4684:27)

and this is the below code one:

Visibility(
            visible:
                (DateTime.now().difference(user.dateOfBirth).inDays / 365) >=
                    18,
            child: CustomTextFormField(
              onChanged: (passNo) => setState(
                () => user = user.copy(passportNumber: passNo),
              ),
              userValue: user.passportNumber,
              userFLName: 'Passport Number',
              keyBoardType: TextInputType.number,
            ),
          ),

and the user Class Looks Like the below code:

class User {
  final String id;
  final String imei;
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  final String imagePath;
  final String passportNumber;
  final String userEmail;

  const User({
    this.id = '',
    this.imei = '',
    this.firstName = '',
    this.lastName = '',
    this.dateOfBirth,
    this.imagePath = '',
    this.passportNumber = '',
    this.userEmail = '',
  });

  User copy({
    String id,
    String imei,
    String firstName,
    String lastName,
    DateTime dateOfBirth,
    String imagePath,
    String passportNumber,
    String userEmail,
  }) =>
      User(
        id: id ?? this.id,
        imei: imei ?? this.imei,
        firstName: firstName ?? this.firstName,
        lastName: lastName ?? this.lastName,
        dateOfBirth: dateOfBirth ?? this.dateOfBirth,
        imagePath: imagePath ?? this.imagePath,
        passportNumber: passportNumber ?? this.passportNumber,
        userEmail: userEmail ?? this.userEmail,
      );

  static User fromJson(Map<String, dynamic> json) => User(
        id: json['id'],
        imei: json['imei'],
        firstName: json['name'],
        lastName: json['lastName'],
        dateOfBirth: DateTime.tryParse(json['dateOfBirth']),
        imagePath: json['imagePath'],
        passportNumber: json['passportNumber'],
        userEmail: json['userEmail'],
      );

  Map<String, dynamic> toJson() => {
        'id': id,
        'imei': imei,
        'name': firstName,
        'lastName': lastName,
        'dateOfBirth': dateOfBirth.toIso8601String(),
        'imagePath': imagePath,
        'passportNumber': passportNumber,
        'userEmail': userEmail,
      };

  @override
  String toString() => 'User{id: $id, name: $firstName}';
}

So what I need to hide or set Visible to false to the Passport text and text form when the age below 18..

Have a look at the below image:

enter image description here

as I tried to use below answer in How to make age validation in flutter :

bool isAdult2(String birthDateString) {
    String datePattern = "dd-MM-yyyy";

    // Current time - at this moment
    DateTime today = DateTime.now();

    // Parsed date to check
    DateTime birthDate = DateFormat(datePattern).parse(birthDateString);

    // Date to check but moved 18 years ahead
    DateTime adultDate = DateTime(
      birthDate.year + 18,
      birthDate.month,
      birthDate.day,
    );

    return adultDate.isBefore(adultDate);
  }

and just change visible property to :

visible: isAdult2(user.dateOfBirth.toString()) ? false : true,

didn't work also, as I found the below error:

======== Exception caught by widgets library =======================================================
The following FormatException was thrown building UserPage(dirty, dependencies: [_LocalizationsScope-[GlobalKey#d2a75], _InheritedTheme], state: _UserPageState#f8143):
Trying to read dd from null at position 0

The relevant error-causing widget was: 
  UserPage file:///Users/mahmoudalharoon/Desktop/InterViewProjects/Mobile%20Technologies/mttest/lib/page/home_page.dart:44:37
When the exception was thrown, this was the stack: 
#0      _DateFormatField.throwFormatException (package:intl/src/intl/date_format_field.dart:87:5)
#1      _DateFormatPatternField.parseField (package:intl/src/intl/date_format_field.dart:337:7)
#2      _DateFormatPatternField.parse (package:intl/src/intl/date_format_field.dart:250:5)
#3      DateFormat._parse (package:intl/src/intl/date_format.dart:374:13)
#4      DateFormat.parse (package:intl/src/intl/date_format.dart:303:7)
...
Mahmoud Al-Haroon
  • 2,239
  • 7
  • 36
  • 72
  • It means that the myVar.microsecondsSinceEpoch is null. – CoderUni Mar 17 '21 at 23:56
  • @Uni it's really wiered i tried it using other way it works but after I restart the app it shows this error `The getter 'microsecondsSinceEpoch' was called on null. Receiver: null Tried calling: microsecondsSinceEpoch` – Mahmoud Al-Haroon Mar 17 '21 at 23:58
  • You might have done something wrong while migrating to null safety. Try to print the variable to check if it is null – CoderUni Mar 17 '21 at 23:59
  • @Uni btw I didn't understant what meaning of error I searched a lot but didn't find solution – Mahmoud Al-Haroon Mar 17 '21 at 23:59
  • The error means that the value of the variable is null. You tried to get .microsecondsSinceEpoch when the value is null. – CoderUni Mar 18 '21 at 00:04
  • @Uni how can I use `.microsecondsSinceEpoch` I didn't tried it :) – Mahmoud Al-Haroon Mar 18 '21 at 00:04
  • 1
    https://stackoverflow.com/questions/50632217/dart-flutter-converting-timestamp – CoderUni Mar 18 '21 at 00:08
  • 1
    When you call `dateOfBirth.toIso8601String()`, `dateOfBirth` likely is null. (`toIso8601String()` likely internally calls `.microsecondsSinceEpoch`.) I don't see any code that guarantees that `dateOfBirth` is initialized to a non-null value. Fix that (or use something like `dateOfBirth?.toIso8601String()`). – jamesdlin Mar 18 '21 at 00:20

0 Answers0