user11874694
user11874694

Reputation:

The parameter 'id' can't have a value of 'null' because of its type, but the implicit default value is 'null'

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}

Upvotes: 3

Views: 9432

Answers (4)

Afid Yoga
Afid Yoga

Reputation: 1

class City {
  int id;
  String name;
  String imageUrl;
  bool isPopular;

  City(
      {required this.id,
      required this.name,
      required this.imageUrl,
      required this.isPopular});
}

Upvotes: 0

DanOps
DanOps

Reputation: 131

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,
   });
  } 

Upvotes: 6

Canada2000
Canada2000

Reputation: 1698

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

Upvotes: 4

enzo
enzo

Reputation: 11486

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

Upvotes: 2

Related Questions