dart 无法无条件调用方法[],因为接收器可以为null

h9vpoimq  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(177)

我试图沿着这个2岁的长笛教程Udemy它的基础上乘坐共享应用程序,但我已经停止。我收到这个错误
无法无条件调用方法“[]”,因为接收器可以为“null”
我真的不知道如何绕过它.我应该检索存储在Firebase实时数据库中的一些用户信息,如用户名,以便在所有应用程序页面中轻松访问,但android studio在制作此模型时给我错误.我已经尝试添加如下空检查,似乎不起作用

检查是否为空

public void run(){

id = snapshot.key;
phone = snapshot.value!['phone'];
email = snapshot.value!['email'];
fullName = snapshot.value!['fullname'];

}
我不确定构造函数是否有错误!

用户数据模型代码

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'];
  }
}

kfgdxczn

kfgdxczn1#

这在Flutter中是零安全的。
有2个选项:

  • 使值nullable
class User{
  final String? fullName;
  final String? email;
  final String? phone;
  final int? id;

  User({
    this.email,
    this.fullName,
    this.phone,
    this.id,
  });

这样,如果快照中没有数据,则user中的变量可以为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'] ?? ''; 
  }
nfs0ujit

nfs0ujit2#

请尝试以下代码:

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']!;
  }
}

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';
  }
}

相关问题