Flutter SharedPreferences存储数据基本使用

发布于:2025-08-15 ⋅ 阅读:(17) ⋅ 点赞:(0)

数据持久化存储
在flutter中使用SharedPreferences 需要异步操作。

请添加图片描述
添加插件

dependencies:
  shared_preferences: ^2.5.3

代码

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MyPage());
}

class MyPage extends StatelessWidget {
  const MyPage({super.key});

  
  Widget build(BuildContext context) {
    return MaterialApp(theme: ThemeData(), home: MyFul());
  }
}

class MyState extends State {
  late String str;

  Future<SharedPreferences> shared = SharedPreferences.getInstance();

  //获取Flag
  void getValue() async {
    SharedPreferences sharedPreferences = await shared;
    bool has = sharedPreferences.containsKey("data");
    if (has) {
      str = sharedPreferences.getString("data")!;
      print(str);
    }else{
      print("没有数据");
    }
  }

  //存储flag
  void setValue(String str) async {
    SharedPreferences sharedPreferences = await shared;
    sharedPreferences.setString("data", str);
    print("存储数据");
  }

  //删除数据
  void delValue(String key) async {
    SharedPreferences sharedPreferences = await shared;
    sharedPreferences.remove(key);
    print("删除数据");
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(""), centerTitle: true),
      body: Column(
        children: [
          OutlinedButton(
            onPressed: () {
              setValue("hello");
            },
            child: Text("存储数据500"),
          ),
          OutlinedButton(
            onPressed: () {
              getValue();
            },
            child: Text("获取数据"),
          ),
          OutlinedButton(
            onPressed: () {
              delValue("data");
            },
            child: Text("删除数据"),
          ),
        ],
      ),
    );
  }
}

class MyFul extends StatefulWidget {
  
  State<StatefulWidget> createState() {
    return MyState();
  }
}


I/flutter (31129): 存储数据
I/flutter (31129): hello
I/flutter (31129): 删除数据
I/flutter (31129): 没有数据


网站公告

今日签到

点亮在社区的每一天
去签到