setState()在构造函数中调用,可以从另一个类更改窗口小部件的状态吗?

时间:2020-05-25 19:11:17

标签: flutter dart

当我尝试通过定义用于设置状态的自定义函数来更改窗口小部件的状态时出现此错误,然后从我创建的新类中调用该函数。

在构造函数中调用的

setState():_MyHomePageState#da7cc(lifecycle 状态:已创建,没有窗口小部件,未安装)

首页:

import 'package:flutter/material.dart';
import 'package:ed_cell/auth_service.dart';
import 'package:flutter/scheduler.dart';

Widget authStatus = Text('Welcome');

class MyHomePage extends StatefulWidget {
  _MyHomePageState myHomePageState= new _MyHomePageState();
  @override
  _MyHomePageState createState() => myHomePageState;
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(10)),
          height: 575,
          child: Row(
            children: <Widget>[
              Column(
                children: [
                  Expanded(
                    child: Image.asset(
                      'assets/images/rocket.png',
                    ),
                  ),
                ],
              ),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Text(
                      'U create\nWe support',
                      style:
                          TextStyle(fontSize: 80, fontWeight: FontWeight.bold),
                    ),
                    authStatus,
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  void onAuthChange() {
     var x=AuthService().status;
    if (AuthService().status == 'Sucessful Sign In') {
      setState(()  {
        authStatus = Text(
          'Welcome',
          style: TextStyle(color: Colors.grey, fontSize: 50),
        );
        print(x);
      });
      print('object'+x);
    } else {
      setState(()  {
        authStatus = RaisedButton(
          onPressed: null,
          color: Colors.deepOrange,
          child: Text(
            'Join Now',
            style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          ),
        );
      });
    }
  }
}

AuthService:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:ed_cell/home_page.dart';

class AuthService{
  String status;

  signIn(email,password){
    FirebaseAuth.instance.signInWithEmailAndPassword(email: email, password: password).then((user){
      print('Signed In '+user.user.uid);
      status='Sucessful Sign In';
    }).catchError((e){
      status='Failure in Sign In';
      print(e);
    });
    MyHomePage().myHomePageState.onAuthChange();
  }
}

1 个答案:

答案 0 :(得分:1)

错误与HomePage尚未插入小部件树有关。您可以按照正确的方法从另一个类调用setState,但是HomePage小部件必须在小部件树中已经存在的位置才能执行setState