text stringlengths 1 372 |
|---|
<code_end> |
<topic_end> |
<topic_start> |
supported types |
although the key-value storage provided by shared_preferences is |
easy and convenient to use, it has limitations: |
<topic_end> |
<topic_start> |
testing support |
it’s a good idea to test code that persists data using shared_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 the setMockInitialValues static method in |
a setUpAll() method in your test files. |
pass in a map of key-value pairs to use as the initial values. |
<code_start> |
SharedPreferences.setMockInitialValues(<String, object>{ |
'counter': 2, |
}); |
<code_end> |
<topic_end> |
<topic_start> |
complete example |
<code_start> |
import 'package:flutter/material.dart'; |
import 'package:shared_preferences/shared_preferences.dart'; |
void main() => runApp(const MyApp()); |
class MyApp extends StatelessWidget { |
const MyApp({super.key}); |
@override |
widget build(BuildContext context) { |
return const MaterialApp( |
title: 'shared preferences demo', |
home: MyHomePage(title: 'shared preferences demo'), |
); |
} |
} |
class MyHomePage extends StatefulWidget { |
const MyHomePage({super.key, required this.title}); |
final string title; |
@override |
State<MyHomePage> createState() => _MyHomePageState(); |
} |
class _MyHomePageState extends State<MyHomePage> { |
int _counter = 0; |
@override |
void initState() { |
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 { |
final prefs = await SharedPreferences.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 { |
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: text(widget.title), |
), |
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.headlineMedium, |
), |
], |
), |
), |
floatingActionButton: FloatingActionButton( |
onPressed: _incrementCounter, |
tooltip: 'increment', |
child: const Icon(Icons.add), |
), |
); |
} |
} |
<code_end> |
<topic_end> |
<topic_start> |
read and write files |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.