Home > Blockchain >  Flutter Error Firebase/Firestore- Null check operator used on a null value
Flutter Error Firebase/Firestore- Null check operator used on a null value

Time:09-24

Im using firebase as database, then i fetch some data from the firestore but throw this error,

"Null check operator used on a null value",

and i dont understand why.

Ps: New to Flutter

heres my HomeScreen Code:

class _HomeState extends State<Home> {
  Map<String, dynamic>? userData = {};
  PanelController _panelController = PanelController();
  Widget build(BuildContext context) {
    getUserData().then((DocumentSnapshot documentSnapshot) async {
      if (documentSnapshot.exists && documentSnapshot.data() != null) {
        setState(() {
          userData = {"data": documentSnapshot.data()};
        });
      }
    });
    return Scaffold(
      appBar: CustomAppbar(
        title: translate("APP_BAR.TITLE.HOME"),
        canBack: false,
      ),
      body: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Text(userData!['data']!['userName']),
        ],
      ),
      drawer: CustomDrawer(),
    );
  }

}

Here my Api Service

final _auth = FirebaseAuth.instance;
final FirebaseFirestore _fireStore = FirebaseFirestore.instance;
final userId = getData(user_uid);

getUserData() {
  return _fireStore.collection('Users').doc(userId).get();
}

CodePudding user response:

You can use the code below it will solve your issue, but check two things do you have all required permissions to fetch data from firebase and also check if the document id is correct ? you can use use if(snapshot.data!.exists) to check if the document exist in the current collection

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

class TestClass extends StatefulWidget {
  const TestClass({Key? key}) : super(key: key);

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

class _TestClassState extends State<TestClass> {
  final _auth = FirebaseAuth.instance;
  final FirebaseFirestore _fireStore = FirebaseFirestore.instance;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<DocumentSnapshot>(
          future: _fireStore
              .collection('Users')
              .doc(_auth.currentUser!.uid)
              .get(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Center(child: Text(snapshot.data!['userName']['name']));
            } else {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
          }),
    );
  }
}
  • Related