The operator '[]' isn't defined for the class 'Object?'

Issue

Bantu saya untuk memecahkan masalah dibawah ini

import 'package:cloud_firestore/cloud_firestore.dart';

class UserModel{
  static const NUMBER = 'number';
  static const ID = 'id';

  String _number = '';
  String _id = '';

  String get number => _number;
  String get id => _id;

  UserModel.fromSnapshot(DocumentSnapshot snapshot){
    _number = snapshot.data()![NUMBER];
    _id = snapshot.data()![ID];
  }
}

With the following errors

lib/models/user_model.dart:16:30: Error: The operator ‘[]’ isn’t
defined for the class ‘Object?’.

  • ‘Object’ is from ‘dart:core’. Try correcting the operator to an existing operator, or defining a ‘[]’ operator.
    _number = snapshot.data()[NUMBER];
    ^ lib/models/user_model.dart:17:26: Error: The operator ‘[]’ isn’t defined for the class ‘Object?’.
  • ‘Object’ is from ‘dart:core’. Try correcting the operator to an existing operator, or defining a ‘[]’ operator.
    _id = snapshot.data()[ID];

Solution

In the recent version of cloud firestore DocumentSnapshot is a generic type so you need to pass a type argument along with it.
Example –

import 'package:cloud_firestore/cloud_firestore.dart';

class UserModel{
  static const NUMBER = 'number';
  static const ID = 'id';

  String _number = '';
  String _id = '';

  String get number => _number;
  String get id => _id;

  UserModel.fromSnapshot(DocumentSnapshot<Map<String,dynamic>> snapshot){
    _number = snapshot.data()![NUMBER];
    _id = snapshot.data()![ID];
  }
}

Answered By – Siddharth jha

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published