Max
Max

Reputation: 1301

The getter 'data' was called on null

I want to read the data from the document of Firestore but it gives an error.

Here is the code:

@override
  Widget build(BuildContext context) {
     final bloc = BlocProvider.of<AuthBloc>(context);
     DocumentSnapshot doc;
    return Scaffold(
      appBar: AppBar(
          title: Text("Your account"), backgroundColor: Colors.blueGrey[900]),
      body: Container(
          color: Colors.blueGrey[800],
          child: Form(
            key: _formKey,
            child: ListView(
              children: <Widget>[
                AccountImage(),
                ListTile(
                  leading: Icon(Icons.account_box, color: Colors.white),
                  title: TextField(
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      hintText: '${doc.data['name']}',
                      hintStyle: TextStyle(color: Colors.white)
                    ),

Screenshot of the error

Upvotes: 0

Views: 2478

Answers (2)

benten
benten

Reputation: 790

if someone facing this problem in 2021 .. the solution is that if you are using ListView.separated the itemCount make problem.. so first initialize a length variable with 0 and assign length variable to itemCount and then using setState assign a new value to the length variable .

Upvotes: 1

Tor-Martin Holen
Tor-Martin Holen

Reputation: 1639

If you want to access a single document in firestore use a FutureBuilder. You are not specifying where you want get your document from in firestore. You need to obtain the DocumentSnapshot from firestore through a Future (or Stream).

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

class FutureExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return FutureBuilder(
        // This assumes you have a project on Firebase with a firestore database.
        future: Firestore.instance.collection("some-path").document("some-id").get(),
        initialData: null,
        builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
          if(snapshot.data == null){
            return CircularProgressIndicator();
          }

          DocumentSnapshot doc = snapshot.data;
          return Text(doc.data['name']);
        });
  }
}

You may find the example in the cloud_firestore repository useful if you haven't configured your app: https://github.com/flutter/plugins/blob/master/packages/cloud_firestore/example/lib/main.dart

Upvotes: 1

Related Questions