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

Issue

I am new to flutter and to programming and I need guidance.
I am building an app where users can create tasks and based on the selected category the corresponding color should be displayed withing the widget.

Currently, I get the error: The body might complete normally, causing ‘null’ to be returned, but the return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.

The function (I get the error on _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;
    }
  }

How I call it:

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

My gut feeling is that this is something simple, but I can’t figure it out.

Solution

The return type from your function is Color, which is non-nullable. Your function should never return null. (If you wanted to allow it to be nullable, it should be Color?.)

Your function body, on the other hand, has a switch statement looking for a few string comparisons. Now I imagine I call your function like this:

_selectedCatColor("Jack")

Your function will not return anything at all, because your switch statement doesn’t handle "Jack". Dart can determine that this could happen, which is why it’s giving you that message.

One way to avoid it is to have a default in your switch statement, for example:

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

Now you will always return a Color.

Answered By – Jon Mountjoy

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *