Home > OS >  The method '[]' can't be unconditionally invoked because the receiver can be 'nu
The method '[]' can't be unconditionally invoked because the receiver can be 'nu

Time:05-06

I want to show the staff list in the Firebase database. However, I am getting the following error.

import 'package:firebase_database/firebase_database.dart';

class Drivers
{
String? name;
String? phone;
String? email;
String? id;
String? car_color;
String? car_model;
String? car_number;

Drivers({this.name, this.phone, this.email, this.car_color, this.car_model, this.car_number});

Drivers.fromSnapshot(DataSnapshot dataSnapshot)
{
id = dataSnapshot.key;
name = dataSnapshot.value["name"];
phone = dataSnapshot.value["phone"];
email = dataSnapshot.value["email"];
car_color = dataSnapshot.value["car_color"];
car_model = dataSnapshot.value["car_model"];
car_number = dataSnapshot.value["car_number"];
}
}

What is the problem with my code??

I tried to put ! symbol after .value but nothing is happen

CodePudding user response:

Try using typecast instead of using '!' .

You can try casting to dynamic. as,

(dataSnapshot.value as dynamic)["name"];

CodePudding user response:

You need to convert object into map before using indexer ([]) on it. Try the code block below

import 'package:firebase_database/firebase_database.dart';

class Drivers
{
String? name;
String? phone;
String? email;
String? id;
String? car_color;
String? car_model;
String? car_number;

Drivers({this.name, this.phone, this.email, this.car_color, this.car_model, this.car_number});

Drivers.fromSnapshot(DataSnapshot dataSnapshot)
{
id = dataSnapshot.key;
name = (dataSnapshot.value as Map)["name"];
phone = (dataSnapshot.value as Map)["phone"];
email = (dataSnapshot.value as Map)["email"];
car_color = (dataSnapshot.value as Map)["car_color"];
car_model = (dataSnapshot.value as Map)["car_model"];
car_number = (dataSnapshot.value as Map)["car_number"];
}
}

CodePudding user response:

The DataSnapshot value can be null so you can not directly try to use the field name.

You should access it using the null operator "!"

Example:

Drivers.fromSnapshot(DataSnapshot dataSnapshot)
{
  id = dataSnapshot.key;
  name = dataSnapshot.value!["name"];
}
  • Related