Flutter本地存储

发布于 1周前 作者 phonegap100 来自 分享

Flutter本地存储可以使用第三方库 shared_preferences实现。

Flutter 本地存储里面常用的一些法方

1、设置值

   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)

2、获取值

SharedPreferences prefs = await SharedPreferences.getInstance();
var data=prefs.getString("name"); 

3、删除值

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key); //删除指定键
prefs.clear();//清空键值对

Flutter 本地存储完整demo

import 'package:flutter/material.dart';

import 'package:shared_preferences/shared_preferences.dart';


class StoragePage extends StatefulWidget {
  StoragePage({Key key}) : super(key: key);

  _StoragePageState createState() => _StoragePageState();
}

class _StoragePageState extends State<StoragePage> {

  _saveData() async{

    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("name", "张三");
    // prefs.setBool(key, value)
    // prefs.setDouble(key, value)
    // prefs.setInt(key, value)
    // prefs.setStringList(key, value)

   
  }
  _getData() async{
     SharedPreferences prefs = await SharedPreferences.getInstance();
     var data=prefs.getString("name");
     print(data);
    
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("本地存储"),
      ),
      body: Center(
        child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
          RaisedButton(
            child: Text('保存数据'),
            onPressed: _saveData,
          ),
          SizedBox(height: 10),
          RaisedButton(
            child: Text('获取数据'),
            onPressed:_getData,
          )         
        ]),
      ),
    );
  }
}
回到顶部