flutter_cache
A: the preface
Some data is often used in the project development (such as account number, token, etc.), and also want to open the app data is still there, all this time you can put some data stored in cache, next time can be obtained directly from the cache, whereby encapsulate a cache class or very be necessary, individual packaging ideas are as follows:
-
Encapsulate a cache class with a singleton, initialize it in the main function, and add some common methods to the class
-
Encapsulate a utility class to hold commonly used key names
-
Yjf -ll/flutter_cache (github.com)
Two: Without further ado, let’s begin
-
To add a cache dependency library to your project, I’m using shared_Preferences
flutter pub add shared_preferences
-
Write the cache key name utility class
// The key name of the value in the cache. The format varies from person to project class CacheKey { static const String TOKEN = 'app_token'; static const String PHONE = 'app_phone'; } Copy the code
-
Writing a cache class
class AppCache { final SharedPreferences sharedPreferences; AppCache._({required this.sharedPreferences}); factory AppCache.create({ required SharedPreferences sharedPreferences, }) => AppCache._( sharedPreferences: sharedPreferences, ); // The cache class takes the singleton pattern static AppCache? _instance; // It must be initialized in main static Future<void> init() async{ _instance ?? = AppCache.create( sharedPreferences:await SharedPreferences.getInstance(), ); } // Simplify the retrieval of cached instances of utility classes to encapsulate some methods below static SharedPreferences get_pre => _instance! .sharedPreferences;// Encapsulate the method to set the token static Future<bool> setToken(String token) async { return await _pre.setString(CacheKey.TOKEN, token); } // Encapsulate the token clearing method static Future<bool> cleanToken() async { return await _pre.setString(CacheKey.TOKEN, ' '); } // Encapsulate the method to obtain the token static String? get token => _pre.getString(CacheKey.TOKEN); // Encapsulate the method for setting phone static Future<bool> setPhone(String phone) async { return _pre.setString(CacheKey.PHONE, phone); } // Encapsulate the method to clear phone static Future<bool> cleanPhone() async { return await _pre.setString(CacheKey.PHONE, ' '); } // Encapsulate the method to get the phone static String? get phone => _pre.getString(CacheKey.PHONE); } Copy the code
-
The home page code is as follows
Future<void> main() async { // If you don't want to use this command, you'll get an error WidgetsFlutterBinding.ensureInitialized(); // Initialize the cache utility class await AppCache.init(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { returnMaterialApp( theme: ThemeData( primarySwatch: Colors.blue, ), home: HomePage(), ); }}class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { String? phone; @override void didChangeDependencies() { super.didChangeDependencies(); getPhone(); } void getPhone() { print('Get mobile phone number'); setState(() { // Get the data you want by calling some of the get methods set by the utility class phone = AppCache.phone; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Cache demo'), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('The current saved mobile phone number is:$phone'), ElevatedButton( onPressed: () async { // Save the phone number await AppCache.setPhone('137xxxxxxxx'); getPhone(); }, child: Text('save'), ), ElevatedButton( onPressed: () async { // Clear the phone number await AppCache.cleanPhone(); getPhone(); }, child: Text('clear'),),),),); }}Copy the code
-
Attach the demo picture, click save, reopen the app, the phone number is still there, end. Thank you for watching, if there is a better way to achieve it, welcome to communicate with us