I am trying to implement a solution to a flutter project where the user selects their Date of Birth from a DateTime picker and then a calculation is done to tell how old the user is. I need it to be able to tell if the user is older than 13 years of age. I am new to Flutter but from what I see the code should execute but currently it just stays at the original value of 0.0. What am I doing wrong?

 class _MyHomePageState extends State<MyHomePage> {
  DateTime _date = new DateTime.now();
  double differenceInYears = 0;

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime dob = await showDatePicker(
      context: context,
      initialDate: _date,
      firstDate: DateTime(1940),
      lastDate: _date,
    );
    Duration dur = _date.difference(dob);
    double differenceInYears = (dur.inDays / 365);
    print('$differenceInYears');
    setState(() {
      return differenceInYears;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: Container(
        padding: new EdgeInsets.all(32.0),
        child: new Column(
          children: <Widget>[
            new Text('$differenceInYears'),
            new RaisedButton(
              child: new Text('Selected Date'),
              onPressed: () {
                _selectDate(context);
              },
            ),
          ],
        ),
      ),
    );
  }


Solution 1: orimdominic

class _MyHomePageState extends State<MyHomePage> {
DateTime _date = new DateTime.now();
double differenceInYears = 0;

Future<Null> _selectDate(BuildContext context) async { final DateTime dob = await showDatePicker( context: context, initialDate: _date, firstDate: DateTime(1940), lastDate: _date, ); Duration dur = _date.difference(dob); // make the change here setState(() { differenceInYears = (dur.inDays / 365); }); }

@override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: Container( padding: new EdgeInsets.all(32.0), child: new Column( children: <Widget>[ new Text('$differenceInYears'), new RaisedButton( child: new Text('Selected Date'), onPressed: () { _selectDate(context); }, ), ], ), ), ); }

In the code listing you provided in your question, you are returning an identifier in the setState method. You are not supposed to do that. You should use the setState to set the state and not return an identifier