使用 SharedPreferences 在Flutter中读取和写入数据
SharedPreferences 是在flutter项目中存储少量数据的最佳选择。共享首选项是一种可以将少量原始数据作为键/值对存储和检索到设备存储文件中的一种方式,例如字符串、整数、浮点数、布尔值,这些数据在应用程序内的 XML 文件中构成您的首选项在设备存储上。例如 – 在 shared_preferences 中存储用户名、登录状态。在Android应用程序中考虑用户是否登录的情况,我们可以将login-logout的状态存储在shared_preferences中,这样用户就不需要写密码了,我们可以一次又一次地把登录状态保存在bool变量中它是少量数据,不需要数据库,我们可以将其存储在 shared_preferences 中以快速访问它。
安装
要使用此插件,请将shared_preferences添加为pubspec.yaml文件中的依赖项。
Note:
To Install and Setup SharedPreferences in Flutter you may refer to the following articles:
- How to Install Shared Preferences in Flutter?
- How to Setup SharedPreferences in Flutter?
例子
下面是一些示例来展示如何使用 shared_preferences。
写入数据
// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();
// Save an integer value to 'num' key.
await prefs.setInt('num', 10);
// Save an boolean value to 'flag' key.
await prefs.setBool('flag', true);
// Save an double value to 'decnum' key.
await prefs.setDouble('decnum', 1.5);
// Save an String value to 'name' key.
await prefs.setString('name', 'Start');
// Save an list of strings to 'items' key.
await prefs.setStringList('items', ['Earth', 'Moon', 'Sun']);
读取数据
// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();
// Save an integer value to 'num' key.
await prefs.setInt('num', 10);
// Save an boolean value to 'flag' key.
await prefs.setBool('flag', true);
// Save an double value to 'decnum' key.
await prefs.setDouble('decnum', 1.5);
// Save an String value to 'name' key.
await prefs.setString('name', 'Start');
// Save an list of strings to 'items' key.
await prefs.setStringList('items', ['Earth', 'Moon', 'Sun']);
删除数据
// Remove data for the 'counter' key.
final success = await prefs.remove('counter');
示例项目
创建一个项目并导入材料包。
Dart
import 'package:flutter/material.dart';
Dart
void main(){
runApp(SharedHome());
}
Dart
class SharedHome extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
_SharedHomeState createState() => _SharedHomeState();
}
class _SharedHomeState extends State {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "SharedPreferences",
theme: ThemeData(primarySwatch: Colors.deepOrange),
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
Dart
import 'package:shared_preferences/shared_preferences.dart';
class Helper {
static String valueSharedPrefrences = '';
// Write DATA
static Future saveUserData(value) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return await sharedPreferences.setInt(valueSharedPrefrences, value);
}
// Read Data
static Future getUserData() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.getInt(valueSharedPrefrences);
}
}
Dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
int _counter = 0;
@override
void initState() {
super.initState();
_loadCounter();
}
// Loading counter value on start
void _loadCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0);
});
}
// Incrementing counter after click
void _incrementCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0) + 1;
prefs.setInt('counter', _counter);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Shared Prefrences")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes
// auto-formatting nicer for build methods.
);
}
}
现在在 void main()函数中调用 runApp() 方法并调用类 SharedHome()。
Dart
void main(){
runApp(SharedHome());
}
现在创建一个名为SharedHome( )的新类,这将是一个有状态的类,因为我们的应用程序确实在运行时改变了它们的状态。并返回 MaterialApp()。
Dart
class SharedHome extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
_SharedHomeState createState() => _SharedHomeState();
}
class _SharedHomeState extends State {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "SharedPreferences",
theme: ThemeData(primarySwatch: Colors.deepOrange),
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
现在我们必须定义我们的 HomeScreen()。在创建 HomePage 之前,让我们创建另一个文件服务。dart
Dart
import 'package:shared_preferences/shared_preferences.dart';
class Helper {
static String valueSharedPrefrences = '';
// Write DATA
static Future saveUserData(value) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return await sharedPreferences.setInt(valueSharedPrefrences, value);
}
// Read Data
static Future getUserData() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.getInt(valueSharedPrefrences);
}
}
在类Helper中,我们有一个静态数据成员valueSharedPrefremnces、成员函数saveUserData 和 getUserData 。在 saverUserData函数中,我们首先获取 shared_preferences 的实例,然后使用这个实例调用 setInt 方法。这基本上将整数值设置为我们的静态成员。首先在 getUserData函数中,我们将实例获取到 shared_preferences。然后返回valueSharedPrefremnces 的值。现在创建类 MyHomePage,我们可以在其中显示实际数据。
Dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
int _counter = 0;
@override
void initState() {
super.initState();
_loadCounter();
}
// Loading counter value on start
void _loadCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0);
});
}
// Incrementing counter after click
void _incrementCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0) + 1;
prefs.setInt('counter', _counter);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Shared Prefrences")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes
// auto-formatting nicer for build methods.
);
}
}
我们有两个函数 loadCounter 和 incrementCounter。在 loadCounter 中,我们从 SharedPreferences 中检索数据。在 incrementCounter 中,我们只是在按下浮动操作按钮时递增值并将其作为参数传递以保存在 SharedPreferences 中。