首页 > 解决方案 > 打开应用程序时,除了第一次打开外,如何一直做一个动作

问题描述

我搜索如何为我的 statefull 小部件的 initstate 的每次调用执行第一次调用之外的操作。

谢谢

标签: flutter

解决方案


最好的方法是使用将值保存到本地存储的SharedPreferences插件。

  1. 将依赖项添加到您的 pubspec.yaml 文件
     dependencies:
          shared_preferences: ^0.5.6
    
  2. 导入插件
     import 'package:shared_preferences/shared_preferences.dart';
    
  3. 引用 SharedPreferences 类
     SharedPreferences prefs = await SharedPreferences.getInstance();
    
  4. 最后检查是否是第一次

     // If the preference firstTime does not exist it means it is the first time
     bool firstTime = prefs.getBool('firstTime') ?? true;
    
     if(firstTime){
    
       // This is the first time the user is opening the app
    
       // Set firstTime preference value to false
       await prefs.setBool('firstTime', false);
    
     } else{
       // The app has been opened before
     }
    

推荐阅读