我在flutter应用中实现了日期选择。然后会显示选定的日期,但是一旦焦点改变,选定的DateTime
对象就会变成null
,而没有任何理由。
要存储DateTime
和其他一些变量,我创建了一个对象,该对象作为最终变量存储在StatefulWidget
类中。此对象还包括Strings
,当DateTime
为空时不会改变。
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;
});
}
}
}
如上所示,DateTime
被DatePicker
选择,然后将结果存储在assignment
对象中。但是,当您单击标题的TextField
时,标题突然变为空。
gif示例:https://gph.is/g/aKn7yqq
答案 0 :(得分:-1)
在状态类中使用声明的变量,如下所示:
import 'package:flutter/material.dart';
import 'package:smartyne/core/assignment.dart';
class AssignmentPage extends StatefulWidget {
@override
_AssignmentPageState createState() => _AssignmentPageState();
}
class _AssignmentPageState extends State<AssignmentPage> {
final bool editMode;
final Assignment assignment;
@override
Widget build(BuildContext context) {
return new Container();
//access it like
//Text(assignment.deadlineAsString),
//instead of
//Text(widget.assignment.deadlineAsString),
}