The non-nullable local variable 'iconData' must be assigned before it can be used in flutter?

Issue

  1. I’m trying to add the switch case statement in IconData and Icon Color when i use they throw some errors
  2. The non-nullable local variable ‘iconData’ must be assigned before it can be used.
    Try giving it an initializer expression, or ensure that it’s assigned on every execution path

TodoAddPage.dart

 class TodoCardPage extends StatefulWidget {
      const TodoCardPage({
        Key? key,
        required this.title,
        required this.iconData,
        required this.iconColor,
      }) : super(key: key);
      final String title;
      final IconData iconData;
      final Color iconColor;

In home page I try to use
homePage.dart

ListView.builder(
                itemCount: (snapshot.data! as QuerySnapshot).docs.length,
                itemBuilder: (context, index) {
                  IconData iconData;
                  Color iconColor;
                  Map<String, dynamic> document =
                      (snapshot.data! as QuerySnapshot).docs[index].data()
                          as Map<String, dynamic>;

                  return TodoCardPage(
                      title: document["title"] == null
                          ? "Hey There"
                          : document["title"],
                      iconData: iconData,
                      iconColor: iconColor,
                      time: "10 PM",
                      value: true,
                      iconBgColor: Colors.white);
                });

Solution

I just found that error thank you so much guys,
the right answer is

ListView.builder(
                itemCount: (snapshot.data! as QuerySnapshot).docs.length,
                itemBuilder: (context, index) {
                  IconData iconData;
                  Color iconColor;
                  Map<String, dynamic> document =
                      (snapshot.data! as QuerySnapshot).docs[index].data()
                          as Map<String, dynamic>;
                  switch (document["category"]) {
                    case "Work":
                      iconData = (Icons.breakfast_dining);
                      iconColor = Colors.red;
                      break;
                    default:
                      iconData = (Icons.add);
                      iconColor = Color.fromARGB(255, 56, 46, 196);
                  }
                  return TodoCardPage(
                      title: document["title"] == null
                          ? "Hey There"
                          : document["title"],
                      iconData: iconData,
                      iconColor: iconColor,
                      time: "10 PM",
                      value: true,
                      iconBgColor: Colors.white);
                });

Answered By – user10993979

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

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