Home > Software engineering >  Null check operator used on a null value in getStringlist with shared preference in flutter getting
Null check operator used on a null value in getStringlist with shared preference in flutter getting

Time:10-21

_CastError (Null check operator used on a null value) getting error to append in a list in variable setstringlist in shared preference

void add() async
{
  var title1 = add_title_controller.text;
  var detail1 = add_detail_controller.text;
  var pref = await SharedPreferences.getInstance();
  final List<String>? todo_title = pref.getStringList('todo_title');
  final List<String>? todo_detail = pref.getStringList('todo_detail');
  var title = todo_title;
  var detail = todo_detail;
  
  title!.add(title1);
  detail!.add(detail1);
  print(title);
  print(detail);
  pref.setStringList('todo_title',title);
  pref.setStringList('todo_detail',detail);
}

getting error to update or append in stringlist in shared preference please help to solve error or there is any another idea ? task is to append in listview.builder and get value from shared pereference.

CodePudding user response:

title and detail may be null so you use ! which means that you sure about it that it is not null which is wrong, so instead of this:

  var title = todo_title;
  var detail = todo_detail;
  
  title!.add(title1);
  detail!.add(detail1);

try this:

List<String> title = todo_title ?? [];
List<String> detail = todo_detail ?? [];

title.add(title1);
detail.add(detail1);

pref.setStringList('todo_title', title);
pref.setStringList('todo_detail', detail);
  • Related