方法“ ancestorStateOfType”在null上被调用。 (循环)

时间:2019-03-15 16:53:21

标签: dart flutter

首先,我是Flutter的初学者。我正在发送表单数据以登录API,并等待成功:来自API的OK消息和UserID。

获取UserID和成功后:API的响应正确,我使用userID将用户发送到仪表板这是我的完整代码;

    class LoginScreen1 extends StatefulWidget {
  @override
  _LoginScreen1State createState() => _LoginScreen1State();
}

class _LoginScreen1State extends State<LoginScreen1> {
  StreamSubscription streamSubscription;

  String formMail, formSifre;

  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();

  final formKey = GlobalKey<FormState>();

  Login login;

  Future<Login> _gonderiGetir(String formMail, String formSifre) async {

    var url = 'MYURL';
    var apiKey = "MYKEY";
    var authPassword = this.formSifre;
    var authMail = this.formMail;
    debugPrint(this.formSifre);

    var response = await http
        .get('$url?Key=12345&mail=${this.formMail}&password=${this.formSifre}');
    debugPrint("Sonuç Bekleniyor.");

    if (response.statusCode == 200) {
      _gelenDegeriBekle();

      return Login.fromJsonMap(json.decode(response.body));
    } else {
      throw Exception("Baglanamadık ${response.statusCode}");
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    /*_gonderiGetir(formSifre, formMail).then((gelenDeger) {
      login = gelenDeger;
      debugPrint(login.UserID);
    });*/
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Color(0xFFF7F8FA),
        child: ListView(
          children: <Widget>[
            Stack(
              children: <Widget>[
                Container(
                  height: 250.0,
                  width: double.infinity,
                ),
                Container(
                  height: 300.0,
                  width: double.infinity,
                  color: Color(0xFFFED428),
                ),
                Positioned(
                    top: 225.0,
                    left: 15.0,
                    right: 15.0,
                    child: Material(
                      elevation: 3.0,
                      borderRadius: BorderRadius.circular(7.0),
                      child: Container(
                        height: 280.0,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(7.0),
                            color: Color(0xF6F6F6)),
                      ),
                    )),
                Positioned(
                  top: 75.0,
                  left: (MediaQuery.of(context).size.width / 2 - 50.0),
                  child: CircleAvatar(
                    radius: 50.0,
                    backgroundImage: NetworkImage(
                        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSHVRLWSF79r7ABstLzXZi_pTcNkAMqx8EtWfIRZiA8mmqcl-Fsqw"),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(40, 235, 40, 15),
                  child: Form(
                    key: formKey,
                    autovalidate: true,
                    child: Column(
                      children: <Widget>[
                        TextFormField(
                          decoration: const InputDecoration(
                            labelStyle: TextStyle(color: Color(0xFFBBBFCB)),
                            icon: Icon(
                              Icons.person,
                              color: Color(0xFFBBBFCB),
                            ),
                            labelText: 'Email *',
                          ),
                          validator: (String girilenVeri) {
                            if (!girilenVeri.contains("@")) {
                              return "Geçerli bir mail adresi giriniz.";
                            } else
                              return null;
                          },
                          controller: _usernameController,
                          onSaved: (deger) => formMail = deger,
                        ),
                        SizedBox(
                          height: 10.0,
                        ),
                        TextFormField(
                          obscureText: true,
                          decoration: const InputDecoration(
                            labelStyle: TextStyle(color: Color(0xFFBBBFCB)),
                            icon: Icon(
                              Icons.lock,
                              color: Color(0xFFBBBFCB),
                            ),
                            labelText: 'Şifre  *',
                          ),
                          validator: (String girilenVeri) {
                            if (girilenVeri.length < 6) {
                              return "Şifre 6 karakterden kısa olamaz.";
                            } else
                              return null;
                          },
                          controller: _passwordController,
                          onSaved: (deger) => formSifre = deger,
                        ),
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(40, 420, 40, 15),
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: RaisedButton(
                            elevation: 0,
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10.0)),
                            color: Color(0xFFFED428),
                            onPressed: () {
                              if (formKey.currentState.validate()) {
                                formKey.currentState.save();
                                _gonderiGetir(formMail, formSifre);
                                debugPrint("OnPress Geldi");
                              }
                            },
                            child: Text(
                              "GİRİŞ",
                              style: TextStyle(fontSize: 20),
                            ),
                          ),
                        ),
                        FlatButton(
                          onPressed: () {},
                          child: Text(
                            "Şifremi Unuttum",
                            style: TextStyle(
                                fontSize: 10, color: Color(0xFFBBBFCB)),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ],
            )
          ],
        ),
      ),
    );
    ;
  }

  void _loginControl() {
    if (formKey.currentState.validate()) {
      formKey.currentState.save();

      //formMail = _usernameController.text;
      //formSifre= _passwordController.text;



      debugPrint("$formSifre ve $formMail");


    }
  }

  void _gelenDegeriBekle() {
    _gonderiGetir(formSifre, formMail).then((gelenDeger) {
      login = gelenDeger;

      if (login.Status != null) {
        debugPrint(login.UserID);
        debugPrint(login.Status);

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => MyHomePage(),
          ),
        );

      }
    });
  }
}

但是我遇到了这个循环错误:

 flutter: asdasd
    flutter: 387ddd00-f5ed-4c9c-87cf-45835bf77a53
    flutter: OK
    [VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'ancestorStateOfType' was called on null.
    Receiver: null
    Tried calling: ancestorStateOfType(Instance of 'TypeMatcher<NavigatorState>')
    #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
    #1      Navigator.of (package:flutter/src/widgets/navigator.dart:1376:19)
    #2      Navigator.pushReplacement (package:flutter/src/widgets/navigator.dart:1055:22)
    #3      _LoginScreen1State._gelenDegeriBekle.<anonymous closure> (package:flutter_apppp/login.dart:247:19)
    #4      _rootRunUnary (dart:async/zone.dart:1132:38)
    #5      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
    #6      _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
    #7      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
    #8      Future._propagateToListeners (dart:async/future_impl.dart:668:32)
    #9      Future._complete (dart:async/future_impl.dart:473:7)
    #10     _SyncCompleter.complete (dart:<…>

我一直收到此错误消息。

1 个答案:

答案 0 :(得分:0)

看起来您有一个循环在您的小部件中连续运行。您正在从_gonderiGetir呼叫_gelenDegeriBekle,也正在从_gelenDegeriBekle呼叫_gonderiGetir。因此,即使您的小部件已删除,它也将永远保持下去(这就是context为null的原因。)

如果您需要连续做某事,我建议改为使用定期计时器来调用它,并确保在处置小部件时停止计时器!