0

I've managed to get the date from 18 years ago today:

var formatter = DateFormat('dd/MM/yyyy');

DateTime today = DateTime.now();
final eighteenY = DateTime(today.year - 18, today.month, today.day);

But now I need to check if the date a user enters is between that date and today's date, and if it is then they are not over the age of 18. How would I go about this? Here is my code:


MaskedTextController _maskDOBController =
MaskedTextController(mask: '00/00/0000');

@override
  Widget build(BuildContext context) {

return Scaffold(

body:

return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
  Container(
    height: 48,
    width: 500,
    child: TextFormField(
      controller: _maskDOBController,
      onChanged: (string){
           setState(() {
             provider.dobString = string;
             dobError = false;
             });
           },
        ),
     ),
   ],
 ),
),

Container(height: 80),

Container(
  GestureDetector(
    onTap: (){
      // if the date a user enters in textfield is between that date and today's date
      // print('user is underage');
    }
    child: Text(
     'Continue'
    ),
  ),
);

Ken White
  • 123,280
  • 14
  • 225
  • 444
James 666
  • 1,560
  • 1
  • 15
  • 27
  • 6
    Does this answer your question? [How to make age validation in flutter](https://stackoverflow.com/questions/61249772/how-to-make-age-validation-in-flutter) – Alex Hartford May 10 '21 at 19:36
  • Yes perfect, thanks man. I haven't actually tried your answer out - but the comment linked me to the first answer of that question which worked – James 666 May 10 '21 at 19:46
  • 1
    You're welcome! Most solutions will work, it's all about what syntax tickles your fancy. – Alex Hartford May 10 '21 at 19:48

1 Answers1

0

This question is a duplicate but I have a solution I use now that I like I felt worth sharing.

You can use an extension to put the function right on DateTime. For example:

extension DateTimeX on DateTime {
  bool isUnderage() =>
      (DateTime(DateTime.now().year, this.month, this.day)
              .isAfter(DateTime.now())
          ? DateTime.now().year - this.year - 1
          : DateTime.now().year - this.year) < 18;
}

void main() {
  final today = DateTime.now();
  final seventeenY = DateTime(today.year - 18, today.month, today.day + 1);
  final eighteenY = DateTime(today.year - 18, today.month, today.day);
  
  print(today.isUnderage());
  print(seventeenY.isUnderage());
  print(eighteenY.isUnderage());
}

It's worth noting this doesn't require intl or any other external package. Paste this right into dartpad.dev to test it out.

Alex Hartford
  • 5,110
  • 2
  • 19
  • 36