Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

docs.flutter.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.

Learn more

Flutter 3.41 is live! Check out theFlutter 3.41 blog post!

Store key-value data on disk

Learn how to use the shared_preferences package to store key-value data.

If you have a relatively small collection of key-values to save, you can use theshared_preferences plugin.

Normally, you would have to write native platform integrations for storing data on each platform. Fortunately, theshared_preferences plugin can be used to persist key-value data to disk on each platform Flutter supports.

This recipe uses the following steps:

  1. Add the dependency.
  2. Save data.
  3. Read data.
  4. Remove data.
Note

1. Add the dependency

#

Before starting, add theshared_preferences package as a dependency.

To add theshared_preferences package as a dependency, runflutter pub add:

flutter pub add shared_preferences

2. Save data

#

To persist data, use the setter methods provided by theSharedPreferences class. Setter methods are available for various primitive types, such assetInt,setBool, andsetString.

Setter methods do two things: First, synchronously update the key-value pair in memory. Then, persist the data to disk.

dart
// Load and obtain the shared preferences for this app.finalprefs=awaitSharedPreferences.getInstance();// Save the counter value to persistent storage under the 'counter' key.awaitprefs.setInt('counter',counter);

3. Read data

#

To read data, use the appropriate getter method provided by theSharedPreferences class. For each setter there is a corresponding getter. For example, you can use thegetInt,getBool, andgetString methods.

dart
finalprefs=awaitSharedPreferences.getInstance();// Try reading the counter value from persistent storage.// If not present, null is returned, so default to 0.finalcounter=prefs.getInt('counter')??0;

Note that the getter methods throw an exception if the persisted value has a different type than the getter method expects.

4. Remove data

#

To delete data, use theremove() method.

dart
finalprefs=awaitSharedPreferences.getInstance();// Remove the counter key-value pair from persistent storage.awaitprefs.remove('counter');

Supported types

#

Although the key-value storage provided byshared_preferences is easy and convenient to use, it has limitations:

  • Only primitive types can be used:int,double,bool,String, andList<String>.
  • It's not designed to store large amounts of data.
  • There is no guarantee that data will be persisted across app restarts.

Testing support

#

It's a good idea to test code that persists data usingshared_preferences. To enable this, the package provides an in-memory mock implementation of the preference store.

To set up your tests to use the mock implementation, call thesetMockInitialValues static method in asetUpAll() method in your test files. Pass in a map of key-value pairs to use as the initial values.

dart
SharedPreferences.setMockInitialValues(<String,Object>{'counter':2});

Complete example

#
dart
import'package:flutter/material.dart';import'package:shared_preferences/shared_preferences.dart';voidmain()=>runApp(constMyApp());classMyAppextendsStatelessWidget{constMyApp({super.key});@overrideWidgetbuild(BuildContextcontext){returnconstMaterialApp(title:'Shared preferences demo',home:MyHomePage(title:'Shared preferences demo'),);}}classMyHomePageextendsStatefulWidget{constMyHomePage({super.key,requiredthis.title});finalStringtitle;@overrideState<MyHomePage>createState()=>_MyHomePageState();}class_MyHomePageStateextendsState<MyHomePage>{int_counter=0;@overridevoidinitState(){super.initState();_loadCounter();}/// Load the initial counter value from persistent storage on start,/// or fallback to 0 if it doesn't exist.Future<void>_loadCounter()async{finalprefs=awaitSharedPreferences.getInstance();setState((){_counter=prefs.getInt('counter')??0;});}/// After a click, increment the counter state and/// asynchronously save it to persistent storage.Future<void>_incrementCounter()async{finalprefs=awaitSharedPreferences.getInstance();setState((){_counter=(prefs.getInt('counter')??0)+1;prefs.setInt('counter',_counter);});}@overrideWidgetbuild(BuildContextcontext){returnScaffold(appBar:AppBar(title:Text(widget.title)),body:Center(child:Column(mainAxisAlignment:MainAxisAlignment.center,children:[constText('You have pushed the button this many times:'),Text('$_counter',style:Theme.of(context).textTheme.headlineMedium,),],),),floatingActionButton:FloatingActionButton(onPressed:_incrementCounter,tooltip:'Increment',child:constIcon(Icons.add),),);}}
Was this page's content helpful?

Unless stated otherwise, the documentation on this site reflects Flutter 3.38.6. Page last updated on 2025-10-28.View source orreport an issue.


[8]ページ先頭

©2009-2026 Movatter.jp