0

I am getting a null value for the 'count' when I am accessing it through the Text widget. But when I print the value of count in the function, it shows the correct value. Please help me to access the value outside of the function so that I can print it.

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

class MyFlexiableAppBar extends StatelessWidget {
  final Subjects subject;
  MyFlexiableAppBar({Key? key, required this.subject}) : super(key: key);

  final user = FirebaseAuth.instance.currentUser;
  Map<String, dynamic>? fetchDoc;
  var db = FirebaseFirestore.instance;
  var count;
  fetchDocs() async {
    DocumentSnapshot classData = await FirebaseFirestore.instance
        .collection('class')
        .doc(subject.batch)
        .get();
    if (classData.exists) {
      fetchDoc = classData.data() as Map<String, dynamic>?;
    }
    count = fetchDoc?['totalStudents'];
    print(count);
  }

  @override
  Widget build(BuildContext context) {
    fetchDocs();
    return Container(
      child: Padding(
        padding: const EdgeInsets.only(top: 120.0, left: 12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(subject.subject,
                style: const TextStyle(
                    color: Colors.white,
                    fontFamily: 'Poppins',
                    fontWeight: FontWeight.w800,
                    fontSize: 30.0)),
            const Padding(padding: EdgeInsets.only(top: 20.0)),
            Row(
              children: <Widget>[
                Text(subject.batch,
                    style: const TextStyle(
                        color: Colors.white,
                        fontFamily: 'Poppins',
                        fontSize: 28.0)),
                const Padding(padding: EdgeInsets.only(left: 50.0)),
                Text('$count',
                    style: const TextStyle(
                        color: Colors.white,
                        fontFamily: 'Poppins',
                        fontSize: 25.0)),
                const Icon(
                  Icons.people,
                  color: Colors.white,
                  size: 30.0,
                ),
              ],
            ),
            const Padding(padding: EdgeInsets.only(top: 25.0)),
            const Text('Total Lectures : 1',
                style: TextStyle(
                    color: Colors.white, fontFamily: 'Poppins', fontSize: 20.0))
          ],
        ),
      ),
    );
  }
}

Image of output console

App image

1
  • 1
    It is because fetchDocs() is executed but after finishing state of layout. Mean you should call count in Text widget after getting data as if there is not data then it will null. For testing purpose use setstate() in fetchDocs() where you're printing count Commented May 6, 2022 at 10:08

1 Answer 1

2

Your fetchDocs() completes after the widget has been build. Thats's why it's null at the time.

Wrap your code in a FutureBuilder, because fetchDocs() returns a Future.

Something along these lines should work:

@override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: fetchDocs(),
        builder: (context, docs) {
          return Container() // <-- your code here
        });
  }

Ideally your fetchDocs() would return the fetchedDocs rather than having a variable in the state.

Similar to this:

 Future<Map<String, dynamic>?> fetchDocs() async {
    var fetched = <String, dynamic>{};
    DocumentSnapshot classData = await FirebaseFirestore.instance
        .collection('class')
        .doc(subject.batch)
        .get();
    if (classData.exists) {
      fetched = classData.data() as Map<String, dynamic>;
    }
    count = fetched['totalStudents'] ?? 0;
    return fetched;
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.