I'm trying to follow along this 2 year old Fluter tutorial on Udemy its based on a ride sharing app, but I've come to a halt. am receiving this error
The method '[]' can't be unconditionally invoked because the receiver can be 'null'
I don't really know how to go around it. I'm supposed to retrieve some user info stored on Firebase Realtime Database like the Username to be easily accessible in all the apps pages, but android studio is giving me errors when making this model. I've tried adding the null checks like below, seems not to work
Null(!) checks apllied
User.fromSnapshot(DataSnapshot snapshot){
id = snapshot.key; phone = snapshot.value!['phone']; email = snapshot.value!['email']; fullName = snapshot.value!['fullname'];
}
I'm not quiet sure if there is a mistake on the constructor!
Code for the user datamodel
import 'package:firebase_database/firebase_database.dart';
class User{
var fullName;
var email;
var phone;
var id;
User({
this.email,
this.fullName,
this.phone,
this.id,
});
User.fromSnapshot(DataSnapshot snapshot){
id = snapshot.key;
phone = snapshot.value['phone'];
email = snapshot.value['email'];
fullName = snapshot.value['fullname'];
}
}
CodePudding user response:
thats null-safety in flutter.
there 2 option:
- make value
nullable
class User{
final String? fullName;
final String? email;
final String? phone;
final int? id;
User({
this.email,
this.fullName,
this.phone,
this.id,
});
with this, your variable in user can be null, if no data from snapshoot
- make it non-null
class User{
final String fullName;
final String email;
final String phone;
final int id;
User({
required this.email,
required this.fullName,
required this.phone,
required this.id,
});
// since its required, it cant be null.
// if snapshot value is null, it will error.
// we can assign another default value
User.fromSnapshot(DataSnapshot snapshot){
id = snapshot.key ?? -1;
// if phone is null, its set to empty string
phone = snapshot.value['phone'] ?? '';
email = snapshot.value['email'] ?? '';
fullName = snapshot.value['fullname'] ?? '';
}
CodePudding user response:
Try the following code:
import 'package:firebase_database/firebase_database.dart';
class User{
var fullName;
var email;
var phone;
var id;
User({
this.email,
this.fullName,
this.phone,
this.id,
});
User.fromSnapshot(DataSnapshot snapshot){
id = snapshot.key;
phone = snapshot.value['phone']!;
email = snapshot.value['email']!;
fullName = snapshot.value['fullname']!;
}
}
or
import 'package:firebase_database/firebase_database.dart';
class User{
var fullName;
var email;
var phone;
var id;
User({
this.email,
this.fullName,
this.phone,
this.id,
});
User.fromSnapshot(DataSnapshot snapshot){
id = snapshot.key;
phone = snapshot.value['phone'] ?? 'phone';
email = snapshot.value['email'] ?? 'email';
fullName = snapshot.value['fullname'] ?? 'fullname';
}
}