【问题标题】:Non-nullable instance field '_selectedDate' must be initialized必须初始化不可为空的实例字段“_selectedDate”
【发布时间】:2021-08-27 17:01:43
【问题描述】:

我正在开发一个费用管理应用程序,在这里我尝试使用 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,
            ),
          ],
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter widget material-design


    【解决方案1】:

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

    无论何时使用它,只需先检查 null:

    
    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 上的 null 安全性,它们具有极高的质量和指导性。 在那里您可以了解何时使用可为空的? 不可为空或late 变量。

    【讨论】:

    • 非常感谢。非常感谢
    【解决方案2】:

    如果要更改 setState 方法中的值,可以使用初始化变量

    DateTime _selectedDate = DateTime.now();
    

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

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 1970-01-01
      • 2021-09-14
      • 2021-09-24
      • 2021-10-11
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多