Home > front end >  I am Getting The operator '[]' isn't defined for the type 'AsyncSnapshot<Obje
I am Getting The operator '[]' isn't defined for the type 'AsyncSnapshot<Obje

Time:12-01

Hey there I am new to flutter and currently encountering an error i.e when i return username i get the error that method is not defined.The error inside builder in futurebuilder when i return textwidget with username. I Added null safety check but still didnt amount to nothing as it gives me an error .I wonder why its hapening .

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class messagebubble extends StatelessWidget {
  // const messagebubble({Key? key}) : super(key: key);
  messagebubble(this.message, this.isMe, this.userID, {required this.key});
  final String message;
  final bool isMe;
  final Key key;
  final String userID;
  @override
  Widget build(BuildContext context) {
    return Row(
        mainAxisAlignment:
            isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: [
          Container(
            decoration: BoxDecoration(
              color: isMe ? Colors.red : Colors.grey,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(12),
                bottomLeft: !isMe ? Radius.circular(0) : Radius.circular(12),
                bottomRight: isMe ? Radius.circular(0) : Radius.circular(12),
              ),
            ),
            width: 150,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
            margin: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
            child: Column(children: [
              FutureBuilder(
                  future: FirebaseFirestore.instance
                      .collection('users')
                      .doc(userID)
                      .get(),
                  builder: (ctx, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return Text('Loading ...');
                    }
                    return Text(
                    snapshot.data!['username'],
                      style: TextStyle(fontWeight: FontWeight.bold),
                    );
                  }),
               Text(
                message,
                style: TextStyle(
                    color:
                        isMe ? Theme.of(context).accentColor : Colors.purple),
              ),
            ]),
          ),
        ]);
  }
}

CodePudding user response:

try use .snapshot() instead of .get() in future

future : FirebaseFirestore.instance
                      .collection('users')
                      .doc(userID)
                      .snapshots()
may it is works

CodePudding user response:

Try to use this

 return Text(
               snapshot.data!['username'] as String,
                  style: TextStyle(fontWeight: FontWeight.bold),);
  • Related