Home > OS >  Expected a value of type 'Map<String, dynamic>', but got one of type '() =>
Expected a value of type 'Map<String, dynamic>', but got one of type '() =>

Time:09-23

I'm developing web app with flutter using Firebase cloud firestore.

I want to get values from firestore, but error occurs and can't get them.

Error;

Expected a value of type 'Map<String, dynamic>', but got one of type '() => Map<String, dynamic>?'

Code;

  Future<String> getData(String collection, String field) async {
    DocumentSnapshot docSnapshot =
        await FirebaseFirestore.instance.collection(collection).doc().get();
    Map<String, dynamic> record = docSnapshot.data as Map<String, dynamic>;
    return record[field];
  }


FutureBuilder(
              future: getData("users", "userName"),
              builder: (context, snapshot) {
                if (snapshot.connectionState != ConnectionState.done) {
                  return const SizedBox(
                    width: 50,
                    child: LinearProgressIndicator(),
                  );
                }

                if (snapshot.hasError) {
                  return SelectableText(snapshot.error.toString());
                }

                if (!snapshot.hasData) {
                  return const Text('No data found');
                }

                return Text('${snapshot.data}');
              },
            )

This code is FutureBuilder that calls getData() and displays an error statement on the screen when an error occurs.


After a bit of research, I found a way to get rid of the error this way. code like this;

Map<String,dynamic> record = new Map<String,dynamic>.from(docSnapshot.data["songs"]);

However, this is grammatically incorrect and will result in a compilation error. Firestore seems to have changed a lot between 2019 and now, is that the cause?

docSnapshot.data["songs"]

This is not valid for DocumentSnapshot.

Can anyone resolve this error? thank you.

Addition 1;

I changed code but other similar error occurred. The first error has been resolved.

    Map<String, dynamic> record = docSnapshot.data() as Map<String, dynamic>;

Expected a value of type 'Map<String, dynamic>', but got one of type 'Null'

Firestore confirmed that the data "userName" was existed correctly.

Img1

CodePudding user response:

I believe DocumentSnapshot.data is a method, so you should change it to: DocumentSnapshot.data()

  • Related