【问题标题】:flutter: error during use shared preference颤动:使用共享偏好期间出错
【发布时间】:2020-06-05 14:26:21
【问题描述】:

我正在尝试使用共享首选项来保持用户登录,并将其放在启动屏幕中,当我运行项目时出现此错误:

[错误:flutter/lib/ui/ui_dart_state.cc(157)] 未处理的异常:

setState() 在 dispose() 之后调用:_SplashScreenState#aa9c8(lifecycle

state: defunct) 如果在 State 上调用 setState() 会发生此错误

不再出现在小部件树中的小部件的对象(例如,

其父小部件不再在其构建中包含该小部件)。这个

当代码从计时器或

动画回调。首选的解决方案是取消计时器或

在 dispose() 回调中停止收听动画。另一个

解决办法是在之前检查这个对象的“mounted”属性

调用 setState() 以确保对象仍在树中。这个

如果 setState() 被调用,错误可能表示内存泄漏

因为另一个对象正在保留对该 State 对象的引用

从树中移除后。为避免内存泄漏,

考虑在 dispose() 期间中断对该对象的引用。

而且数据循环不会停止一次又一次地调用自己。

这是我使用共享偏好的方法:

bool isLoading = true;
init() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        bool isLog = prefs.getBool("islog");
    
        if (isLog == true) {
          String email = prefs.getString("email");
          String pass = prefs.getString("pass");
          
          setState(() {
            signIn(email, pass);
          });
        } else {
          setState(() {
            isLoading = false;
          });
        }
      }
    
    signIn(String email, String pass) async {
        var res = await userProvider.login(email, pass);
    
        var user = userProvider.user.tourist;
        if (res is FailedRequest) {
          Dialogs.showErrorDialog(context, message: res.message, code: res.code);
        } else if (user == true) {
          print("Signing in success");
          await appProvider.countryList();
    
          setState(() {
            Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (context) => BottomScreen()));
          });
          
        }
        userProvider.isLoading = false;
    
        setState(() {
          isLoading = false;
        });
      }

这是我的初始屏幕,其中包含以前的共享偏好代码

@override
  Widget build(BuildContext context) {
    userProvider = Provider.of<UserProvider>(context, listen: false);
    appProvider = Provider.of<AppProvider>(context, listen: false);
    init();
    return isLoading == true
        ? Container(
            color: Colors.white,
            child: Center(
              child: CircularProgressIndicator()),
          )
        : Container(
            child: Scaffold(
              body: Stack(
                children: <Widget>[
                  Container(
                    foregroundDecoration: !AppTheme.isLightTheme
                        ? BoxDecoration(
                            color: AppTheme.getTheme()
                                .backgroundColor
                                .withOpacity(0.4))
                        : null,
                    width: MediaQuery.of(context).size.width,
                    height: MediaQuery.of(context).size.height,
                    child: Image.asset('assets/images/introduction.jpg',
                        fit: BoxFit.cover),
                  ),
                  Column(
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: SizedBox(),
                      ),
                      Center(
                        child: Container(
                          width: 60,
                          height: 60,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(
                              Radius.circular(8.0),
                            ),
                            boxShadow: <BoxShadow>[
                              BoxShadow(
                                  color: AppTheme.getTheme().dividerColor,
                                  offset: Offset(1.1, 1.1),
                                  blurRadius: 10.0),
                            ],
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.all(
                              Radius.circular(8.0),
                            ),
                            child: Image.asset('assets/images/appIcon.png'),
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 16,
                      ),
                      Text(
                        "Voyager",
                        textAlign: TextAlign.left,
                        style: TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 24,
                        ),
                      ),
                      SizedBox(
                        height: 8,
                      ),
                      Text(
                        "Best Trips deals for your holiday",
                        textAlign: TextAlign.left,
                        style: TextStyle(
                          fontSize: 14,
                        ),
                      ),
                      Expanded(
                        flex: 4,
                        child: SizedBox(),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(
                            left: 48, right: 48, bottom: 8, top: 8),
                        child: Container(
                          height: 48,
                          decoration: BoxDecoration(
                            color: AppTheme.getTheme().primaryColor,
                            borderRadius:
                                BorderRadius.all(Radius.circular(24.0)),
                            boxShadow: <BoxShadow>[
                              BoxShadow(
                                color: AppTheme.getTheme().dividerColor,
                                blurRadius: 8,
                                offset: Offset(4, 4),
                              ),
                            ],
                          ),
                          child: Material(
                            color: Colors.transparent,
                            child: InkWell(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(24.0)),
                              highlightColor: Colors.transparent,
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          IntroductionScreen()),
                                );
                              },
                              child: Center(
                                child: Text(
                                  "Get started",
                                  style: TextStyle(
                                      fontWeight: FontWeight.w500,
                                      fontSize: 16,
                                      color: Colors.white),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(
                            bottom:
                                24.0 + MediaQuery.of(context).padding.bottom,
                            top: 16),
                        child: Container(
                          child: Material(
                            color: Colors.transparent,
                            child: InkWell(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(24.0)),
                              highlightColor: Colors.transparent,
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          LoginScreen(context)),
                                );
                              },
                              child: Text(
                                "Already have account? LogIn",
                                textAlign: TextAlign.left,
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          );
  }

那么有人可以帮我解决我的问题吗?

【问题讨论】:

    标签: flutter dart sharedpreferences dispose


    【解决方案1】:

    请在微任务中调用你的 init 函数。

    Future.microtask(() => {init()});
    

    【讨论】:

    • 当我添加你的行时我明白了 '_SplashScreenState' 类没有默认构造函数。尝试使用“_SplashScreenState”中定义的命名构造函数之一
    • 您应该使用有状态的小部件。你可以在这里尝试所有的逻辑。 @override void initState() { super.initState(); //TODO: Future.microtask(//LOGIC) }
    【解决方案2】:

    @Mariam 请使用mounted,

    if (this.mounted){
      setState((){
       //Your state change code goes here
      }); 
    }
    

    【讨论】:

    • 我应该把它放在哪里以及如何,对不起,我之前没有处理过
    【解决方案3】:
    use mounted before setState
    
    if (isLog) {
              String email = prefs.getString("email");
              String pass = prefs.getString("pass");
    
            if(mounted)
              setState(() {
                signIn(email, pass);
              });
            } else {
              if(mounted)
               setState(() {
                 isLoading = false;
               });
            }
    

    【讨论】:

    • 你能写下你的完整代码吗?我认为它会出现在您的初始屏幕中。
    猜你喜欢
    • 1970-01-01
    • 2021-12-09
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    相关资源
    最近更新 更多