how to handle Null values in constructor in my class, Flutter

Solution 1:

Here you have two examples:

If every instance variable are going to be initialized (Your case):

  • Add required keyword in your named parameters
class SidebarItem {
   String title;
   LinearGradient background;
   Icon icon;

  const SidebarItem({
    required this.title,
    required this.background,
    required this.icon,
  });
}

Or a constant if it wont mutate

class SidebarItem {
  final String title;
  final LinearGradient background;
  final Icon icon;

  SidebarItem({
    required this.title,
    required this.background,
    required this.icon,
  });
}

If every instance variable can be null

class SidebarItem {
  String? title;
  LinearGradient? background;
  Icon? icon;
  
  SidebarItem({
    this.title,
    this.background,
    this.icon,
  });
}

Solution 2:

Add ? for optional fields. Add required for mandatory params

class SidebarItem {

  SidebarItem({ this.title, required this.background, required this.icon }); 

  String? title;
  LinearGradient background;
  Icon icon;

}

Solution 3:

please see explanation about setting nullable values here https://stackoverflow.com/a/68058488/13474354

in your case you're missing required keyword before parameter in constructor declaration