Home > Enterprise >  how to solve flutter null value issue in my code?
how to solve flutter null value issue in my code?

Time:12-21

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

enter image description here

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:

  1. changing final String id; to final String? id; in Product.dart
  2. changing final productId = ModalRoute.of(context)!.settings.arguments as String; to final String? productId = ModalRoute.of(context)!.settings.arguments as String?;
  • Related