【问题标题】:The argument type 'DateTime?' can't be assigned to the parameter type 'DateTime'参数类型“日期时间?”不能分配给参数类型“日期时间”
【发布时间】:2022-01-01 00:42:54
【问题描述】:

在书中:Flutter Apprentice First Edition,我有以下代码:

import 'package:flutter/painting.dart';
// 1
enum Importance { low, medium, high }
class GroceryItem {
// 2
final String id;
// 3
final String name;
final Importance importance;
final Color color;
final int quantity;
final DateTime date;
final bool isComplete;
...

而构建方法为

Widget buildDate() {
    final dateFormatter = DateFormat('MMMM dd h:mm a');
    final dateString = dateFormatter.format(item!.date);
    return Text(
      dateString,
      style: TextStyle(decoration: textDecoration),
    );
  }

我有以下错误:

参数类型“日期时间?”不能分配给参数类型“DateTime”。

【问题讨论】:

    标签: flutter dart dart-null-safety


    【解决方案1】:

    这消除了错误-

    final dateString = dateFormatter.format(item!.date as DateTime);
    

    【讨论】:

    • 但是我想知道它是否正确?
    • 是的,这是正确的。这是一种黑客攻击。
    • 如果变量有可能变为空,请不要使用!。使用默认值或使用 if null else 初始化变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 2023-01-11
    • 2021-09-06
    • 2017-04-15
    • 2017-05-12
    • 1970-01-01
    相关资源
    最近更新 更多