【发布时间】:2022-11-24 03:01:43
【问题描述】:
我已经观看了多个解决方案的视频,但找不到解决方案。我已经声明了一个名为 _selectedDate 的 DateTime 类型的变量。首先,编译器要求我初始化变量。我用什么值显示初始化它?此外,我正在执行这样的 NULL 检查:if(_selectedData == null)。一旦我对此进行编码,就会出现一个错误,提示“操作数不能为空,因此条件始终为假,请尝试删除条件。”此外,当我在使用三元运算符时执行 NULL 检查时,编译器会抛出相同的错误。我还尝试使用问号 (?) 将此 DateTime 变量设置为可为空,但它不起作用。
我在我的应用程序中使用日期选择器。单击名为“选择日期”的按钮将打开它。我希望我从日历中选择的任何日期都应该显示在默认情况下写为“No Date Chosen !”的区域。代码如下:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
const NewTransaction(this.addTx, {super.key});
@override
State<NewTransaction> createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
DateTime _selectedDate = DateTime.now();
void _submitData() {
if (_amountController.text.isEmpty) {
return;
}
final enteredTitle = _titleController.text;
final enteredOutput = double.parse(_amountController.text);
widget.addTx(enteredTitle, enteredOutput);
// In the below statement I am not able to perform Null check on _selectedDate (_selectedDate == null).
if (enteredTitle.isEmpty || enteredOutput <= 0 || _selectedDate == null) {
return;
}
widget.addTx(enteredTitle, enteredOutput);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now())
.then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
pickedDate = _selectedDate;
});
});
}
@override
Widget build(BuildContext context) {
return Card(
child: Container(
padding: const EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
TextField(
decoration: const InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData(),
),
TextField(
decoration: const InputDecoration(labelText: 'Amount'),
controller: _amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
),
// ignore: sized_box_for_whitespace
Container(
height: 70,
child: Row(
children: [
Text(_selectedDate == null // Here also I am facing the same issue
? 'No Date Chosen !'
: DateFormat.yMd().format(_selectedDate)),
const SizedBox(width: 25.0),
TextButton(
onPressed: _presentDatePicker,
child: const Text('Choose Date'),
),
],
),
),
ElevatedButton(
onPressed: _submitData,
child: const Text("Add Transaction"),
)
],
),
));
}
}
`
【问题讨论】:
标签: flutter dart null dart-null-safety