【问题标题】:Flutter: How to handle "The default value of an optional parameter must be constant"Flutter:如何处理“可选参数的默认值必须是常量”
【发布时间】:2021-12-25 13:49:36
【问题描述】:

我有一个这样的简单类:

class Restaurant{
  final String id;
  final String name;
  List<Serving> servingList;

  Restaurant({
    required this.id,
    required this.name,
    this.servingList = [], // ERROR
  });
}

默认情况下,我想要servingList 的空列表,稍后将对象添加到此列表中。但我收到错误The default value of an optional parameter must be constant. 我需要做什么?

感谢每一个帮助,谢谢!

【问题讨论】:

    标签: flutter class dart constructor dart-null-safety


    【解决方案1】:

    其实答案就在错误之内。默认值应该是常量。

        class Restaurant{
      final String id;
      final String name;
      List<Serving> servingList;
    
      Restaurant({
        required this.id,
        required this.name,
        this.servingList = const [], // ERROR
      });
    }
    

    您需要在方括号前添加“const”关键字。

    【讨论】:

    • 但是将 const 添加到空列表将使其成为不可修改的列表,这会限制您对列表进行更改,因为它已被标记为 const。你如何解决这个问题?
    猜你喜欢
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    相关资源
    最近更新 更多