0

I updated to cloud_firestore 0.14.0

There's a few break changes:

BREAKING: The get data getter is now a data() method instead.

Before the update this is how I used the getter data

Before:

Future<String> getUsernameFromUserId(String userId) async {
        return (await _userFirestoreCollection.document(userId).get()).data['screenName'];
    }

This is how I use data now.. But doesn't seem to be working... Now:

Future<String> getUsernameFromUserId(String userId) async {
            return (await _userFirestoreCollection.document(userId).get()).data()['screenName'];
        }
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
flutter
  • 6,188
  • 9
  • 45
  • 78

1 Answers1

3

Starting from version cloud_firestore 0.14.0:

The method document() was changed and now you have to use doc() instead, therefore in your code you have to do the following:

    Future<String> getUsernameFromUserId(String userId) async {
        return (await _userFirestoreCollection.doc(userId).get()).data()["screenName"];
    }

Example:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FirstRoute(title: 'First Route'),
    );
  }
}

class FirstRoute extends StatefulWidget {
  FirstRoute({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _FirstRouteState createState() => _FirstRouteState();
}

class _FirstRouteState extends State<FirstRoute> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("test"),
        ),
        body: FutureBuilder(
          future: getData(),
          builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Column(
                children: [
                  Container(
                    height: 27,
                    child: Text(
                      "Name: ${snapshot.data.data()['name']}",
                      overflow: TextOverflow.fade,
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                ],
              );
            } else if (snapshot.connectionState == ConnectionState.none) {
              return Text("No data");
            }
            return CircularProgressIndicator();
          },
        ));
  }

  Future<DocumentSnapshot> getData() async {
    await Firebase.initializeApp();
    return await FirebaseFirestore.instance
        .collection("users")
        .doc("docID")
        .get();
  }
}
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • apologies I do have doc. Just wondering is the .data()["screenName"] syntax ok? – flutter Aug 19 '20 at 12:02
  • it returning null, so was just making sure that's the right way to do it – flutter Aug 19 '20 at 12:04
  • can you try `void getUsernameFromUserId(String userId) { FirebaseFirestore.instance.collection("test").doc(userId).get().then((value) { print(value.data()); }); }` but use your own collection and tell me what do you get – Peter Haddad Aug 19 '20 at 12:05
  • @flutter What did you get? – Peter Haddad Aug 19 '20 at 12:48
  • make sure you call `await Firebase.initializeApp();`, let's say in a futurebuilder, `Future getData() async { await Firebase.initializeApp(); return await FirebaseFirestore.instance.collection("users").doc("docId").get(); }` – Peter Haddad Aug 19 '20 at 14:09
  • I keep getting the method is called on null. Is data()['whatever'] the right way to call? – flutter Aug 19 '20 at 14:28
  • @flutter yes check my edit now.. I just tried this in vscode and its working perfectly.. only use `await Firebase.initializeApp();` once and don't initialize it inside `WidgetsBinding.instance.addPostFrameCallback((_){` I was initializing it under the callback and kept getting null – Peter Haddad Aug 19 '20 at 14:33
  • Thanks Peter, the problem was a method being called when it shouldn't(hence the null). I had an if .. if(snapshot.data==null). Which with the latest update should be snapshot.data(). I thought this might of been caught by the complier. But it wasn't. Anyway thanks for your time. – flutter Aug 19 '20 at 15:40