根据 Flutter 中的选定类别为小部件元素分配不同的颜色

Assigning different color to a widget elements based on a selected category in Flutter

我是 Flutter 和编程的新手,我需要指导。 我正在构建一个应用程序,用户可以在其中创建任务,并且根据所选类别,相应的颜色应该与小部件一起显示。

目前,我收到错误:正文可能正常完成,导致 'null' 被 returned,但 return 类型可能不是- 可空类型。 尝试在末尾添加 return 或 throw 语句。

函数(我在 _selectedCatColor 上得到错误):

Color _selectedCatColor(String catTitile) {
    switch (catTitile) {
      case 'Work':
        return Colors.deepPurple;
      case 'Personal':
        return Colors.green;
      case 'Kids':
        return Colors.red;
      case 'Parents':
        return Colors.indigo;
      case 'Friends':
        return Colors.yellow;
      case 'Misc':
        return Colors.teal.shade800;
    }
  }

我怎么称呼它:

 void submitData() {
   final enteredTitle = titleController.text;
   final enteredCategory = _selectedCategory;
   final enteredColor = _selectedCatColor(_selectedCategory!);

我的直觉是这很简单,但我想不通。

您的函数中的 return 类型是 Color,它是不可为 null 的。你的函数不应该 return null。 (如果你想让它可以为空,它应该是 Color?。)

另一方面,您的函数体有一个 switch 语句,用于查找一些字符串比较。现在我想象我这样调用你的函数:

_selectedCatColor("Jack")

您的函数根本不会 return 任何东西,因为您的 switch 语句不处理“Jack”。 Dart 可以确定这可能发生,这就是它向您提供该消息的原因。

避免它的一种方法是在您的 switch 语句中使用默认值,例如:

case 'Misc':
        return Colors.teal.shade800;
default:
        return Colors.teal.shade800;

现在你将永远return一个Color