I've implemented a date selection in my flutter app. The selected date then gets displayed, but as soon as the focus changes, the selected DateTime object becomes null without any reason.
To store the DateTime and some other variables I've created an object which is stored as a final variable in the StatefulWidget class. This object also includes Strings which don't change when the DateTime becomes null.
import 'package:flutter/material.dart';
import 'package:smartyne/core/assignment.dart';
class AssignmentPage extends StatefulWidget {
final bool editMode;
final Assignment assignment;
AssignmentPage(this.assignment, this.editMode);
@override
_AssignmentPageState createState() => _AssignmentPageState();
}
class _AssignmentPageState extends State<AssignmentPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
...
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(), labelText: "Title"),
onChanged: (value) {
widget.assignment.title = value;
setState(() {});
},
),
...
SizedBox(
height: 16.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
MaterialButton(
child: Text(widget.assignment.deadlineAsString),
onPressed: () {
_showDatePicker();
},
),
...
],
)
],
),
));
}
void _showDatePicker() async {
final DateTime newDeadline = await showDatePicker(
context: context,
initialDate: widget.assignment.deadline == null ? DateTime.now() : widget.assignment.deadline,
firstDate: DateTime(1900),
lastDate: DateTime(2099)
);
if (newDeadline != null && newDeadline != widget.assignment.deadline) {
setState(() {
widget.assignment.deadline = newDeadline;
});
}
}
}
As shown above, the DateTime gets selected by a DatePicker and the result is then stored in the assignment object. But when you click on the TextField for the title, it suddenly turns null.
Example gif: https://gph.is/g/aKn7yqq