deandrehaijiel
deandrehaijiel

Reputation: 153

Flutter The method '[]' can't be unconditionally invoked because the receiver can be 'null'

im having an error stating "The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!')." Ive tried to add the '!' mark as stated and searching online but it doesn't resolve the issue. any ideas?

factory UserModel.fromSnapshot(DocumentSnapshot snapshot) {
    return UserModel(
      name: snapshot.data()["name"],
      email: snapshot.data()['email'],
      phoneNumber: snapshot.data()['phoneNumber'],
      uid: snapshot.data()['uid'],
      isOnline: snapshot.data()['isOnline'],
      profileUrl: snapshot.data()['profileUrl'],
      status: snapshot.data()['status'],
      designation: snapshot.data()['designation'],
      company: snapshot.data()['company'],
    );
  }

Upvotes: -1

Views: 3719

Answers (3)

Abdualiym
Abdualiym

Reputation: 179

  1. Set type to your builder
  2. make variable and assign snapshot.data with !
  3. use variable without any ?, !. Simple as List with []
FutureBuilder<List<Orders>>(                         // 1
   future: futureOrders,
   builder: (context, snapshot) {
      if (!snapshot.hasData) {
         return const Center(child: CircularProgressIndicator());
      } else {
         final List<Orders> orders = snapshot.data!; // 2
         return ListView.builder(
            itemCount: orders.length,                // 3
            itemBuilder: (context, index) => _cartItemWidget(
               id: orders[index].id,                 // 3
               cost: orders[index].cost,             // 3
               date: orders[index].createdAt));      // 3
      }
   },
)

Upvotes: 1

esentis
esentis

Reputation: 4666

That's because if snapshot.data() is null then you can't really access its fields, try null checking it :

snapshot.data()?['name'] ?? ''

And according to docs data method returns non-null map, so you can try also this :

(snapshot.data() as Map<String,dynamic>)['name']

Always assuming you allow null values for name parameter. Otherwise you will need to null check it also

(snapshot.data() as Map<String,dynamic>)['name'] ?? ''

Upvotes: 1

Yunus Emre &#199;elik
Yunus Emre &#199;elik

Reputation: 326

Can you try like this

factory UserModel.fromSnapshot(DocumentSnapshot snapshot) {
    return UserModel(
      name: snapshot.data()["name"] ?? "",
      email: snapshot.data()['email'] ?? "",
      phoneNumber: snapshot.data()['phoneNumber'] ?? 0,
      uid: snapshot.data()['uid'] ?? 0,
      isOnline: snapshot.data()['isOnline'] ?? false,
      profileUrl: snapshot.data()['profileUrl'] ?? ""
    );
  }

Upvotes: 0

Related Questions