避免在onPress按钮中为setState锁定小部件?

时间:2018-10-19 19:13:53

标签: mobile dart flutter

我想用firebase实现简单的登录/注销系统。我已经成功实现了登录/注销系统。登录时,用户将定向到主屏幕,而注销后,用户将定向到登录屏幕(使用RootScreen处理进入主屏幕或登录)。然后,我添加新页面SettingScreen并将注销过程移到设置页面。因此,过程是用户登录->主页(打开抽屉)->设置。但是,执行此操作后,注销过程在“设置屏幕”中变为错误并得到此消息

  

“另一个异常:在窗口小部件时调用setState()或markNeedsBuild()   树被锁住了

奇怪的是,如果我直接从主页登录到设置屏幕,则设置屏幕代码没有问题。

代码(RootScreen和SettingScreen):

import 'package:flutter/material.dart';
import 'login_screen.dart';
import 'home_screen.dart';
import 'setting_screen.dart';
import '../utilities/auth.dart';

class RootScreen extends StatefulWidget {
  RootScreen({this.auth});
  final BaseAuth auth;

  @override
  State<StatefulWidget> createState() => new RootState();
}

enum AuthStatus { notSignedIn, signedIn }

class RootState extends State<RootScreen> {
  AuthStatus authStatus = AuthStatus.notSignedIn;

  @override
  void initState() {
    super.initState();
    widget.auth.currentUser().then((userId) {
      setState(() {
        authStatus =
            userId == null ? AuthStatus.notSignedIn : AuthStatus.signedIn;
      });
    });
  }

  void signedIn() {
    setState(() {
      authStatus = AuthStatus.signedIn;
    });
  }

  void signedOut() {
    setState(() {
      authStatus = AuthStatus.notSignedIn;
    });
  }

  @override
  Widget build(BuildContext context) {
    switch (authStatus) {
      case AuthStatus.notSignedIn:
        return new LoginScreen(auth: widget.auth, onSignedIn: signedIn);
      case AuthStatus.signedIn:
        return new HomeScreen(auth: widget.auth, onSignedOut: signedOut);
    }
  }
}

2. Setting Screen & State:

import 'dart:async';
import 'package:flutter/material.dart';
import '../utilities/auth.dart';

class SettingScreen extends StatefulWidget {
  SettingScreen({this.auth, this.onSignedOut});
  final BaseAuth auth;
  final VoidCallback onSignedOut;
  final String title = "Setting";

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

class SettingState extends State<SettingScreen> {

  void signOut() async {
    setState(() {
      try {
        widget.auth.signOut();
        widget.onSignedOut();
      } catch (e) {
        print(e);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Settings'),
        actions: <Widget>[
          new FlatButton(
            child: Text('Logout',
                style: new TextStyle(fontSize: 17.0, color: Colors.white)),
            onPressed: signOut,
          )
        ],
      ),
      body: new Container(
          child: new Center(
        child: new Text('Settings', style: new TextStyle(fontSize: 32.0)),
      )),
    );
  }
}

主屏幕:

class HomeScreen extends StatefulWidget {
  HomeScreen({this.auth, this.onSignedOut});
  final BaseAuth auth;
  final VoidCallback onSignedOut;

  @override
  HomeState createState() => HomeState();

  void signOut() async {
    try {
      await auth.signOut();
      onSignedOut();
    } catch (e) {
      print(e);
    }
  }
}
//.. Inside the HomeState -> ListTile to Setting Menu
ListTile(
        title:
            Text('Pengaturan', style: new TextStyle(color: Colors.black)),
        onTap: () {
          // Update the state of the app
          // ...
          // Then close the drawer
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => SettingScreen(
                    auth: widget.auth, onSignedOut: widget.onSignedOut)),
          );
        },
      ),
//..

在这种情况下如何避免这种setState和小部件锁定异常?

1 个答案:

答案 0 :(得分:0)

谢谢您基于aziza注释,我通过在抽屉中添加两个Navigator.pop(context)来解决问题,第一个进入抽屉,然后进入其他菜单以避免小部件锁定,第二个退出方法退出,因此回到RootScreen

家庭状态抽屉:

//.. Inside the HomeState -> ListTile to Setting Menu
ListTile(
        title:
            Text('Pengaturan', style: new TextStyle(color: Colors.black)),
        onTap: () {
          // ...
          // Add this
          Navigator.pop(context);
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => SettingScreen(
                    auth: widget.auth, onSignedOut: widget.onSignedOut)),
          );
        },
      ),
//..

设置屏幕中的退出方法:

void signOut() async {
    setState(() {
      try {
        widget.auth.signOut();
        widget.onSignedOut();
        Navigator.pop(context);
      } catch (e) {
        print(e);
      }
    });
  }