Search code examples
flutterflutter-getx

Getx Flutter while updating value throwing null error


Data Model

class DataModel {
  Book? book;
  DataModel({
     this.book,
  });
}

class Book {
  String author;
  Book({
    required this.author,
  });
}

Getx Controller

class BookController extends GetxController{
   var dataModel = DataModel().obs;
  updateAuthor(){
    dataModel.value.book!.author = "";
  }
}

While updating author Getx throwing " null checked used on a null value"

After changing the function to this

  updateAuthor(){
    dataModel.value.book?.author = "";
  }

It is not updating the value, making it null.

Also tried with update method unable to update the value with this type of data model.Class inside class.

I am just trying to update the author but unable to do it.


Solution

  • Here, I will explain what you did wrong,

    First, you made an object of DataModel.

       var dataModel = DataModel().obs;
    

    this dataModel have a book property which you marked it with a ? so you made it nullable.

    so at this point this:

    dataModel.value.book == null ; // true
    

    you didn't assign a real Book instance to the book property, so it's null, so this line:

    dataModel.value.book!.author = ""; // will throw an error
    

    because dataModel.value.book is null.

    what you need to assign a new Book() object to the book property like this, specifying the author property that Book()

      updateAuthor(){
      dataModel.value.book = Book(author: "");
      dataModel.refresh();
      }
    

    now we have a real Book object assigned to book, this will fix the null error you got.