打开页面前显示“空值上使用的空检查操作符”,从数据库中获取后显示在Flutter中

krugob8w  于 2022-12-30  发布在  Flutter
关注(0)|答案(2)|浏览(118)

在我的代码获取数据和显示很好,但在打开该页面显示此错误,并在显示这些细节。在我的代码获取数据从firebase数组类型数据和字符串类型数据。
误差

在该错误页面打开和提取数据后,完成

    • 型号代码**
class Details {
  String? id;
  String? email;
  String? age;
  String? familyChildren;
  List<String>? drinkstalkSE;
  List<String>? drinksUnderstandSE;
  List<String>? drinksUnderstandSE2;

  Details(
      {this.id,
      this.email,
      this.age,
      this.familyChildren,
      this.drinkstalkSE,
      this.drinksUnderstandSE,
      this.drinksUnderstandSE2});

  Details.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    email = json['email'];
    age = json['age'];
    familyChildren = json['familyChildren'];
    drinksUnderstandSE = json['drinksUnderstandSE'].cast<String>();
    drinkstalkSE = json['drinkstalkSE'].cast<String>();
    drinksUnderstandSE2 = json['drinksUnderstandSE2'].cast<String>();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['email'] = this.email;
    data['age'] = this.age;
    data['familyChildren'] = this.familyChildren;

    data['drinksUnderstandSE'] = this.drinksUnderstandSE;
    data['drinkstalkSE'] = this.drinkstalkSE;
    data['drinksUnderstandSE2'] = this.drinksUnderstandSE2;
    return data;
  }
}
    • 后端代码**
Details oneUserDetails = Details();
  Future<void> getDetails() async {
    final sp = context.read<SignInProvider>();

    print(sp.uid);
    final snapshot =
        FirebaseFirestore.instance.collection('users').doc('${sp.uid}').get();

    final result = await snapshot.then(
        (snap) => snap.data() == null ? null : Details.fromJson(snap.data()!));
    print('result is ====> $result');
    setState(() {
      oneUserDetails = result!;
      loading = false;
    });

如何删除页面打开前显示的错误?

fxnxkyjh

fxnxkyjh1#

oneUserDetails被定义为nullable变量,它可能为空,但您在尝试访问drinksUnderstandSE或其他属性时使用了Text小工具中的!,这是错误的,因为您使用!时说我非常确定它不是空,因此将!更改为?

Text( 'drink understand : ${oneUserDetails?.drinksUnderstandSE}'), // this will show like this => drink understand : null

也可以设置默认值以避免显示null,如下所示:

Text( 'drink understand : ${oneUserDetails?.drinksUnderstandSE ?? 'default variable'}'), // this will show like this => drink understand : default variable
5kgi1eie

5kgi1eie2#

详细信息-一个用户详细信息;
将此更改为:

Details oneUserDetails = Details();

相关问题