在 null 上调用了 getter 'size'

时间:2021-03-09 19:27:38

标签: flutter google-cloud-firestore

当我按下Telefon ile Giriş Yap 按钮时出现此错误。应用程序仍然按照我想要的方式工作。我不明白为什么会出现这个错误。当使用 Telefon ile Giriş Yap 按钮出现此错误时,按下 Google ile Giriş Yap 按钮时不会出现此错误尽管它们都以类似的形式编码。这是我的代码:

//ekkran yetmeme problemi var!!!!

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:sby_cpal_demo/Helpers/AtaWidget.dart';
import 'package:sby_cpal_demo/Helpers/SignInProvider.dart';
import 'package:sby_cpal_demo/Pages/SinifListeleriPage.dart';
import 'package:sby_cpal_demo/main.dart';
import 'package:flutter_signin_button/flutter_signin_button.dart';
import 'package:flutter_signin_button/button_list.dart';

class GirisPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return GirisPageState();
  }
}

class GirisPageState extends State<GirisPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  final FirebaseAuth _auth = FirebaseAuth.instance;
  TextEditingController _emailController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  TextEditingController _schoolNoController = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  bool _success;
  String _message;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      //resizeToAvoidBottomPadding: false,
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: Icon(Icons.account_box),
        title: Text("GİRİŞ"),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.home),
            onPressed: () {
              if(AtaWidget.of(context).kullaniciadi == "" || AtaWidget.of(context).kullaniciadi == " "
              || AtaWidget.of(context).kullaniciadi == null ){
                AlertDialog alertDialog = new AlertDialog(title: Text("*UYARI: "), content: Text("Kayıt yada giriş işlemi "
                    "tamamlanmandan sayfadan çıkmak üzeresiniz!!", style: TextStyle(color: Colors.orange),),
                  actions: [
                    RaisedButton(
                      child: Text("Yine de Çık"), color: Colors.green,
                      onPressed: (){
                        AtaWidget.of(context).kayitadi = null;
                        goToMyHomePage();
                        Navigator.of(context,rootNavigator: true).pop("dialog");
                        },
                    ),
                ],);
                showDialog(context: context, builder: (_)=> alertDialog);
              } else { goToMyHomePage(); }
            },
          ),
          Builder(
            builder: (context)=>IconButton(
                icon: Icon(Icons.logout), onPressed: ()async{
              await _auth.signOut();
              setState(() {
                AtaWidget.of(context).kullaniciadi = " ";
                AtaWidget.of(context).kullanicimail = " ";
                _success = null;
                AtaWidget.of(context).personelGiris = false;
                AtaWidget.of(context).ogrenciGiris = false;
              });
              if (await GoogleSignIn().isSignedIn()) {
                print("google user");
                await GoogleSignIn().disconnect();
                await GoogleSignIn().signOut();
              }
              Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => MyHomePage()));
              Scaffold.of(context).showSnackBar(SnackBar(
                content: Text("Başarıyla çıkış yapıldı"),
              ));
            }),
          )
        ],
      ),
      body: Center(
        child: Form(
            key: _formKey,
            child: Padding(
              padding: const EdgeInsets.only(left: 36.0, right: 36),
              child: ListView(
               // mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(height: 30,),
                  ListTile(
                    leading: Icon(Icons.warning_amber_rounded, color: Colors.red[500], size: 30),
                    title: Text("Google ile direkt giriş yapabilirsiniz. İlk giriş için erişim izni istenebilir.",
                      style: TextStyle(color: Colors.redAccent, fontSize: 17, fontStyle: FontStyle.italic, fontWeight: FontWeight.w500),),
                  ),
                  Visibility(visible: AtaWidget.of(context).personelGiris,
                    child: FloatingActionButton.extended(
                        icon: Icon(Icons.phone_rounded, color: Colors.black,), backgroundColor: Colors.indigoAccent,
                        label: Text("Telefon ile giriş yap", style: TextStyle(fontWeight: FontWeight.bold)),
                      onPressed: () async {

                        Widget setupAlertDialogContainer() {
                          return Container(
                            height: 300, width: 300,
                            child: StreamBuilder(
                                stream: FirebaseFirestore.instance.collection("kadro_ogrt").orderBy("sıra").snapshots(),
                                builder: (context, snapshot){
                                  final _querySnapshot = snapshot.data;
                                  return ListView.builder(
                                      itemCount: _querySnapshot.size,
                                      itemBuilder: (BuildContext context, int index){
                                        final map = _querySnapshot.docs[index].data();
                                        return Column(
                                          children: [
                                            ListTile(
                                               title: Text(map["isim"],
                                                   style: TextStyle(fontWeight: FontWeight.bold, fontStyle: FontStyle.italic)),
                                               onTap: (){
                                                 Navigator.of(context, rootNavigator: true).pop('dialog');
                                                _signInWithPhone(map["tel"], map["isim"]);
                                                },),
                                            Divider(thickness: 1,),]);
                                      });
                                }),
                          );
                        }
                        showDialog(context: context, builder: (_) {
                          return AlertDialog(
                            title: Text("PERSONEL LİSTESİ"),
                            content: setupAlertDialogContainer(),
                          );
                        });

                    }),
                  ),
                  SizedBox(height: 20,),
                  
                  SignInProvider(
                      infoText: "Google ile giriş yap",
                      buttonType: Buttons.Google,
                      signInMethod: () async {

                          Widget setupAlertDialogContainer() {
                            return Container(
                              height: 500, width: 300,
                              child: StreamBuilder(
                                  stream: AtaWidget.of(context).personelGiris == true ?
                                  FirebaseFirestore.instance.collection("kadro_ogrt").orderBy("sıra").snapshots()
                                  : FirebaseFirestore.instance.collection("siniflar").snapshots(),

                                  builder: (context, snapshot){
                                    if (snapshot.connectionState == ConnectionState.waiting) {
                                      return Center(child: CircularProgressIndicator(),
                                      );
                                    } else if (snapshot.hasError) {
                                      return Center(child: Icon(Icons.error, size: 40),
                                      );
                                    } else if (snapshot.data == null) {
                                      return Center( child: CircularProgressIndicator(),
                                      );
                                    }
                                    final querySnapshot = snapshot.data;

                                    if(AtaWidget.of(context).personelGiris == true){
                                      return ListView.builder(
                                          itemCount: querySnapshot.size,
                                          itemBuilder: (BuildContext context, int index){
                                            final map = querySnapshot.docs[index].data();
                                            return Column(
                                                children: [
                                                  ListTile(
                                                    title: Text(map["isim"],
                                                        style: TextStyle(fontWeight: FontWeight.bold, fontStyle: FontStyle.italic)),
                                                    onTap: ()async{
                                                      if(map["mail"] == "" || map["mail"] == " " || map["mail"] == null ){
                                                        Navigator.of(context, rootNavigator: true).pop('dialog');
                                                        AlertDialog alertDialog = new AlertDialog(
                                                          title: Text("Hata: "), content: Text("Güvenlik sebeiyle Google ile giriş "
                                                            "yapabilmeniz için sisteme kayıtlı bir gmail hesabınız olmalıdır. Telefonla "
                                                            "giriş yaptıktan sonra GMAİL adresinizi **KADROMUZ** bölümünden kendi "
                                                            "sayfanıza ekleyerek Google ile girişi kullanabilirsiniz."),
                                                        );
                                                        showDialog(context: context, builder: (_) => alertDialog);
                                                      } else {
                                                        Navigator.of(context, rootNavigator: true).pop('dialog');
                                                        _signInWithGoogle(map["mail"], map["isim"]);
                                                      }
                                                    },),
                                                  Divider(thickness: 1,),]);
                                          });
                                    } else {
                                      return GridView.builder(
                                          shrinkWrap: true,
                                          itemCount: querySnapshot.size,
                                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                              mainAxisSpacing: 10, crossAxisSpacing: 10, crossAxisCount: 3),
                                          itemBuilder: (context, index) {
                                            final map = querySnapshot.docs[index].data();
                                            final id = querySnapshot.docs[index].id;
                                            return Container(
                                              color: Colors.blueGrey,
                                              child: GestureDetector(
                                                onTap: ()async{
                                                  Navigator.push(context, MaterialPageRoute(builder: (context)=>
                                                      SinifListeleriPage(map: map, id: id)));
                                                },
                                                child: GridTile(
                                                  child: Center(
                                                    child: Text(map["sinif"], style: TextStyle(color: Colors.black,
                                                        fontWeight: FontWeight.bold, fontSize: 18), textAlign: TextAlign.center,),
                                                  ),
                                                ),
                                              ),
                                            );
                                          });
                                    }

                                  }),
                            );
                          }
                          showDialog(context: context, builder: (_) {
                            return AlertDialog(
                              title: Text("SINIF LİSTESİ"),
                              content: setupAlertDialogContainer(),
                            );
                          });
                        } , // TODO: Google ile giriş
                    ),

                  SizedBox(height: 20,),
                  Container(
                    alignment: Alignment.center,
                    child: SingleChildScrollView(
                      physics: ClampingScrollPhysics(),
                      child: Center(
                        child: Text(_success == null ? '' : _message ?? '',
                          style: TextStyle(backgroundColor: Colors.yellow, fontWeight: FontWeight.bold,
                              fontSize: 17, color: Colors.black),
                          textAlign: TextAlign.center,),
                      ),
                    )
                    ),
                ],
              ),
            )),
      ),
    );
  }

  @override
  void dispose() {
    //! Widget kapatıldığında controllerları temizle
    _schoolNoController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  

// *****HERE IS WHERE I GET THE ERROR*****
  void _signInWithPhone(String no, String isim) async {
    if (AtaWidget.of(context).kullaniciadi == "" || AtaWidget.of(context).kullaniciadi == " " ||
        AtaWidget.of(context).kullaniciadi == null ) {

      _auth.verifyPhoneNumber(
        phoneNumber: no, timeout: Duration(seconds: 120),
        verificationCompleted: (AuthCredential credential) async {
          final UserCredential userCredential = await _auth.signInWithCredential(credential);
          final User user = userCredential.user;

          setState(() {
            AtaWidget.of(context).kullaniciadi = isim;
          });
          debugPrint("atawidget: " + AtaWidget.of(context).kullaniciadi);
          Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (context) => MyHomePage(),));
        },
        verificationFailed: (FirebaseAuthException e) {
          setState(() {
            _message = e.toString();
            _success = false;
          });
        },
        codeSent: (String verificationId, int resendToken) async {
          // Update the UI - wait for the user to enter the SMS code
          String smsCode = 'xxxx';

          // Create a PhoneAuthCredential with the code
          PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider
              .credential(verificationId: verificationId, smsCode: smsCode);

          // Sign the user in (or link) with the credential
          await _auth.signInWithCredential(phoneAuthCredential);
        },
        codeAutoRetrievalTimeout: (String verificationId) {
          // Auto-resolution timed out...
        },
      );
    } else {
      setState(() {
        _message = "*HATA: Önce uygulamadan çıkış yapmalısınız.";
        _success = false;
      });
    }
  }


  
  _signInWithGoogle(String mail, String isim) async{
    if (AtaWidget.of(context).kullaniciadi == "" || AtaWidget.of(context).kullaniciadi == " " ||
        AtaWidget.of(context).kullaniciadi == null ) {

      try {
        final GoogleSignInAccount googleUser = await GoogleSignIn().signIn();
        final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
        final GoogleAuthCredential credential = GoogleAuthProvider.credential(
            accessToken: googleAuth.accessToken, idToken: googleAuth.idToken
        );
        final UserCredential userCredential = await _auth.signInWithCredential(credential);
        final User user = userCredential.user;
        debugPrint(user.email.toString());

        if(user.email.toString() == mail){
          AtaWidget.of(context).kullaniciadi = isim;
          debugPrint("atawidget: "+AtaWidget.of(context).kullaniciadi);
          setState(() {});
          Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> MyHomePage(),));
        } else {
          AlertDialog alertDialog = new AlertDialog(
            title: Text("Hata: "), content: Text("Seçilen kullanıcı adı ile sistemde kayıtlı mail adresi uyuşmamaktadır. "
              "Lütfen kullanıcı adını doğru seçtiğinizden emin olunuz. "),
          );
          showDialog(context: context, builder: (_) => alertDialog);
          await _auth.signOut();
          setState(() {
            AtaWidget.of(context).kullaniciadi = " ";
            AtaWidget.of(context).kullanicimail = " ";
          });
          if (await GoogleSignIn().isSignedIn()) {
            print("google user");
            await GoogleSignIn().disconnect();
            await GoogleSignIn().signOut();
          }
        }
      } on FirebaseAuthException catch(e){
        setState(() {
          _message = e.toString();
          _success = false;
          AtaWidget.of(context).kullaniciadi = " ";
        });
      } catch (e) {
        setState(() {
          _message = e.toString();
          _success = false;
          AtaWidget.of(context).kullaniciadi = " ";
        });
      }
    }
    else {
      setState(() {
        _message = "*HATA: Önce uygulamadan çıkış yapmalısınız.";
        _success = false;
      });
  }
  }

  void goToMyHomePage() async {
    await Navigator.push(context, MaterialPageRoute(builder: (context) => MyHomePage()));
  }

  void goToGirisPage() async {
    await Navigator.push(context, MaterialPageRoute(builder: (context) => GirisPage()));
  }

  
}

我知道这是很长的时间来看看这个。这是我的终端输出:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#12628):
The getter 'size' was called on null.
Receiver: null
Tried calling: size

The relevant error-causing widget was: 
  StreamBuilder<QuerySnapshot> file:///C:/ornekler/sby_cpal_demo/lib/Pages/GirisPage.dart:242:36
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      GirisPageState.build.<anonymous closure>.setupAlertDialogContainer.<anonymous closure> (package:sby_cpal_demo/Pages/GirisPage.dart:247:65)
#2      StreamBuilder.build (package:flutter/src/widgets/async.dart:525:81)
#3      _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:129:48)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

快照中的数据不会立即可用,您必须在显示使用快照数据的小部件之前检查快照连接状态,在呈现需要快照的小部件之前检查快照是否具有以下代码段的数据数据。

if (snapshot.hasData) {
//Your Widget here
}

答案 1 :(得分:0)

我认为问题出在这里:

    ListView.builder(
                                      
    itemCount: _querySnapshot.size,

在您的代码中 _querySnapshot 是 snapshot.data 数据有 length 尝试改变它的长度。