Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

firebase - Why calling an async function whose defination is given in another program returns null or Future<type> instance for the first time as output?

Hello Im very to the flutter framework, so please let me know if im going wrong anywhere and the appropriate way of doing the things.

this is a drawerPage.dar file

In this file im trying to call a function getData for retrieving the data from firebase,this fucntion is in Database.dart file.

Database.dart

In the Database.dart file i wrote the getData function inside which im retrieving a particular record from the firebase and storing in a global variable. And then im trying to print the global variable in the drawerPage.dart file.But here when ever i run the program, for the first time the variable is having a null value and upon hot reload the actual value is getting stored in the variable.Please let me know how can i get rid of this problem.

output

drawerPageOutput

drawerPage.dart

import 'package:attendee/constants.dart';
import 'package:attendee/models/userdeails.dart';
import 'package:attendee/pages/profile.dart';
import 'package:attendee/services/authentication_service.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:attendee/services/database.dart';
import 'package:provider/provider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:attendee/pages/userdetails.dart';

class StudentDashboard extends StatefulWidget {

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

class _StudentDashboardState extends State<StudentDashboard> {
  userdetails userdetail;

   final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  final AuthenticationService _auth = AuthenticationService();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    DatabaseService().getData('email');
    final drawerHeader = UserAccountsDrawerHeader(
      accountName: Text(userName),
      accountEmail: Text('${result}'),
      currentAccountPicture
          : CircleAvatar(
        child: FlutterLogo(size: 42.0),
        backgroundColor: Colors.white,
    );
    final drawerItems = ListView(
      children: <Widget>[
        drawerHeader,
        ListTile(
          title: Row(
            children: <Widget>[
              Icon(Icons.perm_identity_outlined),
              Text(' Profile'),
            ],
          ),
          onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (context)=>Profile())),
        ),
        ListTile(
          title: Text('To page 2'),
          onTap: () => Navigator.of(context).push(_NewPage(2)),
        ),
        ListTile(
          title:Row(
            children: <Widget>[
              Icon(Icons.exit_to_app_rounded),
              Text(' Logout'),
            ],
          ),
          onTap: () async {
            await _auth.signOut();
            Navigator.of(context).pushNamed('/homepage');
          },
        ),
      ],
    );
    return StreamProvider<List<userdetails>>.value(
      value: DatabaseService().students,
      initialData: [],
      child: SafeArea(
        child: Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.lightGreen,
              title: Text('Student Welcome'),
              actions: <Widget>[
                TextButton.icon(
                     onPressed: () async {
                      await _auth.signOut();
                      Navigator.of(context).pushNamed('/homepage');
                     
                    },
                    icon: Icon(Icons.person),
                    label: Text('Logout'))
              ],
            ),
            body:
               UserDetails(),
      

            drawer: GestureDetector(
              onTap: display,
              child: Drawer(
                child: drawerItems,
              ),
            ),
        ),
      ),
    );
  }

   display() async{
     await DatabaseService().getData('email');
  }
}

// <Null> means this route returns nothing.
class _NewPage extends MaterialPageRoute<Null> {
  _NewPage(int id)
      : super(builder: (BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page $id'),
        elevation: 1.0,
      ),
      body: Center(
        child: Text('Page $id'),
      ),
    );
  });
}

database.dart

import 'package:attendee/models/userdeails.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_icons/flutter_icons.dart';

import '../constants.dart';

class DatabaseService{

  final String uid;
  DatabaseService({this.uid});

//collection reference
final CollectionReference user_details=FirebaseFirestore.instance.collection('users');`
final CollectionReference tutor_details` `=FirebaseFirestore.instance.collection("tutors");`


Future updateStudentData(String fullname,String mobilenumber,String `email,String rollno,String tutorid,String role) async {`
return await user_details.doc(uid).set({
  'fullname' : fullname,
  'mobilenumber': mobilenumber,
  'email' : email,
  'rollno': rollno,
  'tutorid': tutorid,
  'role' : role,//FMERT series
});
  }

Future updateTutorData(String fullname,String mobilenumber,String `email,String rollno,String tutorid,String role) async {`
    return await tutor_details.doc(uid).set({
      'fullname' : fullname,
      'mobilenumber': mobilenumber,
      'email' : email,
      'rollno': rollno,
      'tutorid': tutorid,
      'role' : role,//FMERT series
    });
  }
  //studentDetails from snapshot
  List<userdetails> _studentDetailsFromSnapshot(QuerySnapshot snapshot){
    return snapshot.docs.map((doc){
      return userdetails(
        fullname: doc.data()['fullname'] ?? '',
        mobilenumber: doc.data()['mobilenumber'] ?? '',
        email: doc.data()['email'] ?? '',
        rollno: doc.data()['rollno'] ?? '',
        tutorid: doc.data()['tutorid'] ?? '',
        //role: doc.data()['role'] ?? '',
      );
    }).toList();
  }

  //get students stream
  Stream<List<userdetails>> get students {
    return user_details.snapshots()
        .map(_studentDetailsFromSnapshot);
  }

  //tutorsDetails from snapshot
  List<userdetails> _tutorDetailsFromSnapshot(QuerySnapshot snapshot){
    return snapshot.docs.map((doc){
      return userdetails(
        fullname: doc.data()['fullname'] ?? '',
        mobilenumber: doc.data()['mobilenumber'] ?? '',
        email: doc.data()['email'] ?? '',
        rollno: doc.data()['rollno'] ?? '',
        tutorid: doc.data()['tutorid'] ?? '',
      );
    }).toList();
  }

  //get tutors stream
  Stream<List<userdetails>> get tutors {
    return user_details.snapshots()
        .map(_studentDetailsFromSnapshot);
  }

  void display() {
    tutor_details.get().then((querySnapshot) {
      querySnapshot.docs.forEach((result) {
        print(result.data());
      });
    });
  }

   getData (String string) async{
    String userId = await FirebaseAuth.instance.currentUser.uid;
    final document = isTutor ? `FirebaseFirestore.instance.doc('tutors/$userId') :`
await FirebaseFirestore.instance.doc('users/$userId'); 
    document.get().then((DocumentSnapshot) async {
      if(string =='role') {
        checkRole = DocumentSnapshot.data()[string].toString();
        print('$checkRole inside getData Function');
        //return checkRole;
        print(checkRole);
      }
      else {
        print(result);
        result = await DocumentSnapshot.data()[string].toString();
        print('${DocumentSnapshot.data()[string].toString()} in the `database else block');`
        //return result;
      }
    //print(document("name"));
    });
  }
  }

After changes terminaloutput draweroutput

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...