I want to keep null as a default value for product id, as it'll be later auto-generated, but I can't due to the flutter null safety check. this is the instance creation code where I want to keep id = null:
var _editedProduct = Product(
id: null,
title: '',
price: 0,
description: '',
imageUrl: '',
);
and here is the code for my Product.dart file:
import 'package:flutter/material.dart';
class Product with ChangeNotifier {
final String id;
final String title;
final String description;
final double price;
final String imageUrl;
bool isFavorite;
Product({
required this.id,
required this.title,
required this.description,
required this.price,
required this.imageUrl,
this.isFavorite = false,
});
void toggleFavoriteStatus() {
isFavorite = !isFavorite;
notifyListeners();
}
}
A screenshot of the error
CodePudding user response:
While you like to have id
default value as null, First you need to accept nullable data. For final String id;
will be final String? id;
the default value can be provided on constructor by removing required
to act as optional. id
will have null
by default.
To use id
you need to check if it is null or not.
If you are sure it contains data use !
at the end like id!
, or
provide a default value like id??"default"
, or
if(Product.id!=null){...}
class Product with ChangeNotifier {
final String? id;
final String title;
final String description;
final double price;
final String imageUrl;
bool isFavorite;
Product({
this.id,
required this.title,
required this.description,
required this.price,
required this.imageUrl,
this.isFavorite = false,
});
...
Learn more about null-safety
CodePudding user response:
Following changes solved my issue:
- changing
final String id;
tofinal String? id;
in Product.dart - changing
final productId = ModalRoute.of(context)!.settings.arguments as String;
tofinal String? productId = ModalRoute.of(context)!.settings.arguments as String?;