必须初始化不可为 null 的实例字段“_selectedDate”

Non-nullable instance field '_selectedDate' must be initialized

我正在用 flutter 开发一个费用管理应用程序,我在这里尝试使用 showDatePicker() 创建一个 DateTimePicker。因此在我的 presentDateTimePicker() 函数中,我正在调用 showDatePicker() 方法。

我正在为 selectedDate 创建一个变量,我没有将它初始化为当前值,因为它会根据用户输入而改变。

在我的 setState() 方法中,我使用 _selectedDate = pickedDate.

仍然显示错误“不可为空的实例字段”

我的插件

//flutter imports
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:intl/intl.dart';

class NewTransaction extends StatefulWidget {
  final Function addTx;

  NewTransaction(this.addTx);

  @override
  _NewTransactionState createState() => _NewTransactionState();
}

class _NewTransactionState extends State<NewTransaction> {
  final _titleController = TextEditingController();
  final _amountController = TextEditingController();
  final _brandNameControlller = TextEditingController();
  DateTime _selectedDate;

  void _submitData() {
    final enteredTitle = _titleController.text;
    final enteredAmount = double.parse(_amountController.text);
    final enteredBrandName = _brandNameControlller.text;

    if (enteredTitle.isEmpty || enteredAmount <= 0) {
      return;
    }

    widget.addTx(
      enteredTitle,
      enteredAmount,
      enteredBrandName,
    );
    Navigator.of(context).pop();
  }

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

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 5,
      child: Container(
        padding: EdgeInsets.all(10),
        child: Column(
          children: <Widget>[
            TextField(
              autocorrect: true,
              decoration: InputDecoration(labelText: 'Title'),
              controller: _titleController,
              onSubmitted: (_) => _submitData,
              //onChanged: (val) {
              //titleInput = val;
              //},
            ),
            TextField(
              autocorrect: true,
              decoration: InputDecoration(labelText: 'Amount'),
              controller: _amountController,
              keyboardType: TextInputType.number,
              onSubmitted: (_) => _submitData,
              //onChanged: (val) => amountInput = val,
            ),
            TextField(
              autocorrect: true,
              decoration: InputDecoration(labelText: 'Brand Name'),
              controller: _brandNameControlller,
              onSubmitted: (_) => _submitData,
              //onChanged: (val) => brandInput = val,
            ),
            Container(
              height: 70,
              child: Row(
                children: <Widget>[
                  Text(_selectedDate == null
                      ? 'No Date Chosen'
                      : 'Picked Date: ${DateFormat.yMd().format(_selectedDate)}'),
                  FlatButton(
                    onPressed: _presentDateTimePicker,
                    child: Text(
                      'Chose Date',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    textColor: Theme.of(context).primaryColor,
                  ),
                ],
              ),
            ),
            RaisedButton(
              onPressed: _submitData,
              child: Text('Add Transaction'),
              color: Theme.of(context).primaryColor,
              textColor: Theme.of(context).textTheme.button!.color,
            ),
          ],
        ),
      ),
    );
  }
}

如果您要更改 setState 方法中的值,您可以使用

初始化变量
DateTime _selectedDate = DateTime.now();

并将其格式化为您向用户显示的格式,这将消除错误,如果您要在每次用户选择日期时更改它,将当前日期视为起始值可以为用户提供起点作为参考。

如果该值可以为 null,只需将变量标记为 null DateTime? _selectedDate;

无论何时使用它,只需先检查是否为空:


Text(_selectedDate == null
? 'No Date Chosen'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate!)}'),
// Here you do know that the value can't be null so you assert to the compiler that

查看有关空安全的 official docs,它们质量极高且很有启发性。 在那里您可以阅读有关何时使用可空 ? 不可空或 late 变量的信息。

在这种情况下有一个解决方法

初始化日期

DateTime _selectedDate = DateTime.parse('0000-00-00');

以及稍后在文本小部件中 而不是

Text(_selectedDate == null
? 'No Date Chosen'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate!)}'),

使用

Text(_selectedDate == DateTime.parse('0000-00-00')
? 'No Date Chosen'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate!)}'),