Skip to content

Instantly share code, notes, and snippets.

@mingsai
Created December 13, 2019 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mingsai/05f913bac7d0a1d62fd7ec31189988fc to your computer and use it in GitHub Desktop.
Save mingsai/05f913bac7d0a1d62fd7ec31189988fc to your computer and use it in GitHub Desktop.
Stateless Widget - Shared Preferences Example
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.blue),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Saving data'),
),
body: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
child: Text('Read'),
onPressed: () {
_read();
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
child: Text('Save'),
onPressed: () {
_save();
},
),
),
],
),
);
}
// Replace these two methods in the examples that follow
_read() async {
final prefs = await SharedPreferences.getInstance();
final key = 'my_int_key';
final value = prefs.getInt(key) ?? 0;
print('read: $value');
}
_save() async {
final prefs = await SharedPreferences.getInstance();
final key = 'my_int_key';
final value = 42;
prefs.setInt(key, value);
print('saved $value');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment