3

I am following a Flutter tutorial that has such a following code, but code doesn't work on my computer, and I don't know how to fix it:

import 'package:flutter/foundation.dart';

class CartItem {
  final String id;

  CartItem({
    @required this.id,
  });
}

But I get such these errors:

The parameter 'id' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.dartmissing_default_value_for_parameter
{String id}
  • 1
    you're telling "id" that it can never be null... it should be "String?" instead of "String". I'll recommend you reading more about null safety: https://dart.dev/null-safety Also, "@required" is now "required". You're using a newest version of Flutter and that example is old. – Mariano Zorrilla Sep 29 '21 at 00:39
  • @MarianoZorrilla: What is the difference between using `late` before the variable or `?` mark after it? –  Sep 29 '21 at 00:51
  • "late" is just like the word is saying, you'll init the variable "late" instead of during object construction but it can only be initialized once. Optional means that the object can also be null – Mariano Zorrilla Sep 29 '21 at 14:49

4 Answers4

5

The latest dart version now supports sound null safety. The tutorial must be using an old version.

To indicate that a variable might have the value null, just add ? to its type declaration:

class CartItem {
  final String? id = null;
  CartItem({
     this.id,
   });
  } 

or

class CartItem {
  final String? id;
  CartItem({
     this.id,
   });
  } 
DanOps
  • 121
  • 2
  • 7
4

You have a few options depending on your own project...

Option1: Make id nullable, you can keep @required or remove it.

class CartItem {
  final String? id;

  CartItem({
    this.id,
  });
}

Option2: Give a default (non-null) value to id

class CartItem {
  final String id;

  CartItem({
    this.id="",
  });
}

more in this link

Canada2000
  • 1,688
  • 6
  • 14
2

You can just replace @required this.id with required this.id.

enzo
  • 9,861
  • 3
  • 15
  • 38
0
class City {
  int id;
  String name;
  String imageUrl;
  bool isPopular;

  City(
      {required this.id,
      required this.name,
      required this.imageUrl,
      required this.isPopular});
}
Afid Yoga
  • 1
  • 1