如何在共享首选项中使用scoped_model?

时间:2019-01-10 21:50:35

标签: dart flutter

我正在使用scoped_model将状态管理添加到我的聊天应用程序中。

我的问题是如何将scoped_model与共享首选项一起使用。因此,在应用启动时,模型状态将填充共享首选项中的值。例如,将从共享的首选项中检索存储的username,然后以UserModel username状态存储。

我已经看过但没有找到教程该怎么做。

我从FlutterCinematic main.dart找到了这个样本:

void main() async { 
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    runApp(ScopedModel<AppModel>(
    model: AppModel(sharedPreferences), child: CinematicApp()));
    }

这是最好的方法吗? 最好的方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

我知道距问这个问题已经有一段时间了。但我还是还是要回答。

我在使用共享首选项和范围模型开发Android应用程序时遇到了同样的问题。我的想法是在应用启动时初始化scopedmodel中的值。我的方法是在模型的构造函数中调用函数。

比方说,我的范围模型是:

class AppModel extends Model {
   String variable1;
   String variable2;
   int variable3;

   //Getter functions go here

   //Setter function (though not a pure setter but a function that sets the values)
   void setValues() {
        SharedPreferences.getInstance().then(
            (prefs) {
                        variable1 = prefs.getString('var1');
                        variable2 = prefs.getString('var2');
                        variable3 = prefs.getInt('var3');
          ));
       }

     AppModel(
           setValues();
      );
}

现在,当您在Material应用程序之前初始化模型时,其值将被初始化。

相关问题