Calculation of age using Dart

Asked

Viewed 94 times

-2

I have a field that is for "date of birth" Textformfield and I have a mask to facilitate user typing (dd/mm/yyyy) but I need a validation that, depending on what the user type is not possible to register him being under 18 and above 70 years of age and in case this verification would be for when the user click the button register for example.

    FractionallySizedBox(
                            widthFactor: 0.9,
                            child: Container(
                                width: MediaQuery
                                    .of(context)
                                    .size
                                    .width / 1,
                                height: 50,
                                child: TextFormField(
                                  controller: dateController,
                                  keyboardType: TextInputType.number,
                                
                                  
                                  inputFormatters: [
                                    FilteringTextInputFormatter.digitsOnly,
                                    DataInputFormatter(),
                                  ],
                                  validator: (value) {
                                    if (value == null || value.isEmpty) {
                                      return '';
                                    }
                                      
                                    return null;
                                  },
                                  
                                 
                                  decoration: InputDecoration(
                                      errorStyle: TextStyle(
                                        fontSize: 0.0,
                                      ),
                                      prefixIcon: Icon(
                                      Icons.calendar_today_outlined,
                                        color: darkGreenColor,
                                      ),
                                      border: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(10),
                                      ),
                                      labelText: 'Data de Nascimento*',
                                      labelStyle: TextStyle(color: Colors.black26)),
                                )
                                ),
                          ),

1 answer

0


First get the value the user typed using your controller:

String textoDataNascimento = dateController.text; //Exemplo:'30/04/1950'

Remember to check if this string is valid (if for example it has the number of characters required).

You have not provided in your question, but as you are using a DataInputFormatter() I imagine this text comes in format DD/MM/AAAA. If this is the case, we need to get the information separately:

List<String> campos = textoDataNascimento.split('/');
int dia = int.parse(campos[0]);
int mes = int.parse(campos[1]);
int ano = int.parse(campos[2]);
DateTime nascimento = DateTime(ano,mes,dia);
DateTime hoje = DateTime.now();

And with that we create two objects Datetime. It is a class that represents an instant in time, and has useful methods and attributes.

One of them is the method Difference(), which returns the difference between two Datetime objects. Many Responses by Stackoverflow in English recommend this approach. That is, you calculate the difference between these two objects, check the number of days, and divide by 365:

print(hoje.difference(nascimento).inDays~/365); //Não faça isso

However, as the documentation of this method says, this difference is only the number of seconds between a date and another, and consequently will be wrong in leap years, for example. At the present moment of this response, I tested this approach with someone born on 04/28/1950 and were returned 71 years when the difference is only 70.

There are other external libraries cited in the above answers that also provide this functionality, however, to calculate only one age, I believe the easiest way is to calculate manually, obtaining and comparing with today’s date:

int idade = hoje.year - nascimento.year;
if (hoje.month<nascimento.month)
  idade--;
else if (hoje.month==nascimento.month){
  if (hoje.day<nascimento.day)
    idade--;
}
print(idade);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.