flutter 无法在IF条件下以及执行TERNARY操作时对DateTime类型变量执行NULL CHECK

oug3syen  于 2022-11-25  发布在  Flutter
关注(0)|答案(1)|浏览(121)

我已经看了很多视频,但是没有找到解决方案。我声明了一个DateTime类型的变量,名为_selectedDate。首先,编译器要求我初始化变量。用什么值显示我初始化它?另外,我正在执行一个NULL检查,如下所示:

if(_selectedData == null )

当我编写这个代码的时候,出现了一个错误,显示为The operand cannot be null,so the condition is always false , try removing the condition .。另外,当我使用三元运算符执行NULL检查时,编译器也抛出了同样的错误。我也尝试过使用问号(?)将这个DateTime变量设置为可空,但它不起作用。
我在我的应用程序中使用日期选择器。单击名为“选择日期”的按钮即可打开。我希望我从日历中选择的任何日期都应显示在默认情况下写有“未选择日期!”的区域中。代码如下所示:

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"),
          )
        ],
      ),
    ));
  }
}
elcex8rz

elcex8rz1#

你用DateTime.now();初始化你的_selectedDate变量,所以编译器警告你它不能为空是绝对正常的。
您可以删除DateTime.now();来解决您的问题,还可以按如下方式切换set State:_selectedDate = pickedDate;
然后在showDatePicker结果上,使用pickedDate调用setState方法,即使它为null,如下所示:

showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2019),
        lastDate: DateTime.now())
    .then((pickedDate) {
  // if (pickedDate == null) {
  //  return;
  // }
  setState(() {
    _selectedDate = pickedDate!;
  });
});

相关问题