Rudransh Singh Mahra
Rudransh Singh Mahra

Reputation: 115

How to resolve The operator '[]' isn't defined for the type 'Object'?

Currently working on Grocery Application but getting an error: The operator '[]' isn't defined for the type 'Object'. Tried searching online but got no solution. Flutter Developers help me resolve the error.

import 'package:cloud_firestore/cloud_firestore.dart';

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

  late String _number;
  late String _id;

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

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

Error ScreenShot

UPDATE: ERROR FIXED

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>> documentSnapshot){
    _number = documentSnapshot.data()![NUMBER];
    _id = documentSnapshot.data()![ID];
  }
}

Upvotes: 1

Views: 2392

Answers (1)

julemand101
julemand101

Reputation: 31289

An important detail for DocumentSnapshot is that it is defined with a generic:

DocumentSnapshot<T extends Object?>

https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentSnapshot-class.html

Where T is then used by the data() method signature:

data() → T?

If we don't specify anything in the generic part, Dart will in this case automatically assume T is Object?. This is a problem in your case since Object? does not have any [String] operator.

You therefore need to explicit tell Dart what type you expect T to be by doing something like this:

UserModel.fromSnapShot(DocumentSnapshot<Map<String,dynamic>> documentSnapshot){

Here we tell Dart that T in DocumentSnapshot should be Map<String,dynamic> so when we call data(), Dart can assume that you get a Map<String,dynamic>? typed object back (notice it will always add ? at the end because that is how data() is defined).

Upvotes: 2

Related Questions