title: How to get the data in User Model class from firebase flutter
body: <p>I am creating app using <code>Firebase</code>.</p>
  <p>My <code>Users.dart</code> file:</p>
  <pre><code>  class Users{
  
    final String id;
    final String profileName;
    final String userName;
    final String url;
    final String email;
    final String bio;
  
    Users({
      this.id,
      this.profileName,
      this.userName,
      this.url,
      this.email,
      this.bio
    });
  
    factory Users.fromDocument(DocumentSnapshot doc){
      return Users(
          id: doc.data()['id'],
          email: doc.data()['email'],
          userName: doc.data()['userName'],
          url: doc.data()['url'],
          profileName: doc.data()['profileName'],
          bio: doc.data()['bio']
      );
    }
  }
  </code></pre>
  <p>Now Look at <code>Auth.dart</code> file:</p>
  <pre><code>import 'package:cloud_firestore/cloud_firestore.dart';
  import  'package:firebase_auth/firebase_auth.dart' as auth;
  import 'package:mms/models/User.dart';
  import 'package:mms/screens/Homepage.dart';
  
  class Auth{
  
    final auth.FirebaseAuth _auth = auth.FirebaseAuth.instance;
    final firebaseUser = auth.FirebaseAuth.instance.currentUser;
  
    Users _userFromFirebaseUser(auth.User user){
      return user != null ? Users(id: user.uid) : null;
    }
  
    Future login(String email, String password) async {
      try{
        auth.UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
        auth.User user = result.user;
        return _userFromFirebaseUser(user);
      } catch(e){
        print(e.toString());
        return null;
      }
    }
  
    //signup and create user on Firebase
    Future register(String name, String email, String password) async {
      try{
        auth.UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
        auth.User user = result.user;
        return _userFromFirebaseUser(user);
      } catch(e){
        print(e.toString());
        return null;
      }
    }
    //signing out from the app
    Future signOut() async {
      try{
        return await _auth.signOut();
      } catch(e){
        print(e.toString());
        return null;
      }
    }
  }
  </code></pre>
  <p>Now I am saving the data when user create the account on my app to firestore as per below:</p>
  <pre><code>saveUserInfoToFirestore() async {
      var firebaseUser = auth.FirebaseAuth.instance.currentUser;
      DocumentSnapshot documentSnapshot =
          await firestoreInstance.collection('users').doc(firebaseUser.uid).get();
  
      if (!documentSnapshot.exists) {
        //final profileName = await Navigator.push(context, MaterialPageRoute(builder: (context) =&gt; SignupPage()));
        firestoreInstance.collection(&quot;users&quot;).doc(firebaseUser.uid).set({
          &quot;uid&quot;: firebaseUser.uid,
          &quot;profileName&quot;: _name,
          &quot;email&quot;: firebaseUser.email,
          &quot;timestamp&quot;: timestamp,
          &quot;bio&quot;: &quot;&quot;
        }).then((_) =&gt; print('Success'));
        documentSnapshot = await firestoreInstance
            .collection('users')
            .doc(firebaseUser.uid)
            .get();
      }
      currentUser = Users.fromDocument(documentSnapshot); //currentUser is the instance of Users model class
    }
  }
  </code></pre>
  <p>Now whenever I call <code>users.id</code> I am getting error that</p>
  <pre><code>The method '[]' was called on null.
  Receiver: null
  Tried calling: [](&quot;id&quot;)
  </code></pre>
  <p>I have called <code>users.id</code> as per below in my <code>Search.dart</code>:</p>
  <pre><code>import 'package:cloud_firestore/cloud_firestore.dart';
  import 'package:flutter/cupertino.dart';
  import 'package:flutter/material.dart';
  import 'package:mms/models/Progress.dart';
  import 'package:mms/models/User.dart';
  import 'package:mms/screens/ActivityFeed.dart';
  import 'package:mms/screens/Homepage.dart';
  
  class SearchPage extends StatefulWidget {
  
    @override
    _SearchPageState createState() =&gt; _SearchPageState();
  }
  
  class _SearchPageState extends State&lt;SearchPage&gt; {
    TextEditingController searchTextEditingController = TextEditingController();
    Future&lt;QuerySnapshot&gt; futureSearchResults;
    String profileName;
  
    void initState(){
      super.initState();
      getProfileName();
    }
    clear() {
      searchTextEditingController.clear();
    }
    Future&lt;void&gt; getProfileName() async {
      final firestoreInstance = FirebaseFirestore.instance;
      firestoreInstance
          .collection(&quot;users&quot;)
          .doc(firebaseUser.uid)
          .get()
          .then((value) {
        setState(() {
          profileName = value.data()[&quot;profileName&quot;].toString();
        });
      });
    }
    searchController(String str) {
      Future&lt;QuerySnapshot&gt; allUsers = FirebaseFirestore.instance
          .collection(&quot;users&quot;)
          .where(&quot;profileName&quot;, isGreaterThanOrEqualTo: str)
          .get();
      setState(() {
        futureSearchResults = allUsers;
      });
    }
  
    Container displayNoSearchResultScreen() {
      final Orientation orientation = MediaQuery.of(context).orientation;
      return Container(
        child: Center(
          child: ListView(
            shrinkWrap: true,
            children: &lt;Widget&gt;[
              Icon(
                Icons.group,
                color: Colors.grey,
                size: 200.0,
              ),
              Text(
                'Find Users',
                textAlign: TextAlign.center,
                style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                    fontSize: 50.0),
              )
            ],
          ),
        ),
      );
    }
  
    displayUsersFoundScreen() {
      return FutureBuilder(
          future: futureSearchResults, builder: (context, dataSnapshot) {
            if(!dataSnapshot.hasData){
              return circularProgress();
            }
  
  
            //This part is also not working properly
            List&lt;UserResult&gt; searchUserResult = [];
            dataSnapshot.data.docs.forEach((document){
              Users users = Users.fromDocument(document);
              UserResult userResult = UserResult(users);
              searchUserResult.add(userResult);
            });
            return ListView(children: searchUserResult,);
      });
    }
  
    AppBar searchPageHeader() {
      return AppBar(
        backgroundColor: Colors.black,
        title: TextFormField(
          style: TextStyle(fontSize: 18.0, color: Colors.white),
          controller: searchTextEditingController,
          decoration: InputDecoration(
              hintText: &quot;Search&quot;,
              hintStyle: TextStyle(color: Colors.grey),
              enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.grey)),
              focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.white)),
              filled: true,
              prefixIcon: Icon(
                Icons.person_pin,
                color: Colors.white,
                size: 30.0,
              ),
              suffixIcon: IconButton(
                icon: Icon(
                  Icons.clear,
                  color: Colors.white,
                ),
                onPressed: clear,
              )),
          onFieldSubmitted: searchController,
        ),
      );
    }
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        backgroundColor: Colors.black,
        appBar: searchPageHeader(),
        body: futureSearchResults == null
            ? displayNoSearchResultScreen()
            : displayUsersFoundScreen(),
      );
    }
  }
  
  class UserResult extends StatelessWidget {
  
    final Users users;
    UserResult(this.users);
  
    @override
    Widget build(BuildContext context) {
      return Padding(
          padding: EdgeInsets.all(3.0),
        child: Container(
          color: Colors.white54,
          child: Column(
            children: &lt;Widget&gt;[
              GestureDetector(
                onTap: () =&gt; showProfile(context, profileId: users.id),//Here I have called but not working
                child: ListTile(
                  //leading: CircleAvatar(backgroundColor: Colors.blue, backgroundImage: CachedNetworkImageProvider(users.url),),
                  title: Text(users.profileName, style: TextStyle(
                    color: Colors.black, fontSize: 16.0, fontWeight: FontWeight.bold,
                  ),),
               
                ),
              )
            ],
          ),
        ),
      );
    }
  }
  </code></pre>
  <p>What is the mistake I am not able find that? If anybody can know the solution than please tell me?</p>