Flutter中的localstorage之shared_preferences

423 阅读1分钟
  1. pubspec.yaml文件中添加依赖

    dependencies:
      shared_preferences: ^2.0.15
    
  2. 导入

    import 'package:shared_preferences/shared_preferences.dart';
    
  3. 增删改查

    // 增
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(key, value)
    prefs.setBool(key, value)
    prefs.setDouble(key, value)
    prefs.setInt(key, value)
    prefs.setStringList(key, value)
        
    // 删
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove(key); //删除指定键
    prefs.clear();//清空键值对// 改: 改和增是一样的,只需要再执行一次setXXX()方法即可覆盖之前的数据。// 查
    Set<String> getKeys() => new Set<~>.from(_preferenceCache.keys);
    dynamic get(String key) => _preferenceCache[key];
    int getInt(String key) => _preferenceCache[key];
    bool getBool(String key) => _preferenceCache[key];
    double getDouble(String key) => _preferenceCache[key];
    String getString(String key) => _preferenceCache[key];
    List<String> getStringList(String key) {
        List<Object> list = _preferenceCache[key];
        if (list != null && list is! List<String>) {
            list = list.cast<String>().toList();
            _preferenceCache[key] = list;
        }
        return list;
    }
    

    List cast()

    Returns a view of this list as a list of R instances.
    ​
    If this list contains only instances of R, all read operations will work correctly. If any operation tries to access an element that is not an instance of R, the access will throw instead.
    

实例

// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.// ignore_for_file: public_member_api_docsimport 'dart:async';
​
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
​
void main() {
  runApp(const MyApp());
}
​
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
​
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'SharedPreferences Demo',
      home: SharedPreferencesDemo(),
    );
  }
}
​
class SharedPreferencesDemo extends StatefulWidget {
  const SharedPreferencesDemo({Key? key}) : super(key: key);
​
  @override
  SharedPreferencesDemoState createState() => SharedPreferencesDemoState();
}
​
class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  late Future<int> _counter;
​
  Future<void> _incrementCounter() async {
    final SharedPreferences prefs = await _prefs;
    final int counter = (prefs.getInt('counter') ?? 0) + 1;
​
    setState(() {
      _counter = prefs.setInt('counter', counter).then((bool success) {
        return counter;
      });
    });
  }
​
  @override
  void initState() {
    super.initState();
    _counter = _prefs.then((SharedPreferences prefs) {
      return prefs.getInt('counter') ?? 0;
    });
  }
​
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SharedPreferences Demo'),
      ),
      body: Center(
          child: FutureBuilder<int>(
              future: _counter,
              builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return const CircularProgressIndicator();
                  default:
                    if (snapshot.hasError) {
                      return Text('Error: ${snapshot.error}');
                    } else {
                      return Text(
                        'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n'
                        'This should persist across restarts.',
                      );
                    }
                }
              })),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

\