Skip to content

Instantly share code, notes, and snippets.

@slightfoot
Created June 20, 2018 20:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save slightfoot/d549282ac0a5466505db8ffa92279d25 to your computer and use it in GitHub Desktop.
Save slightfoot/d549282ac0a5466505db8ffa92279d25 to your computer and use it in GitHub Desktop.
SharedPreferencesBuilder thingy
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPreferencesBuilder<T> extends StatelessWidget {
final String pref;
final AsyncWidgetBuilder<T> builder;
const SharedPreferencesBuilder({
Key key,
@required this.pref,
@required this.builder,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return FutureBuilder<T>(
future: _future(),
builder: (BuildContext context, AsyncSnapshot<T> snapshot) {
return this.builder(context, snapshot);
});
}
Future<T> _future() async {
return (await SharedPreferences.getInstance()).get(pref);
}
}
class Example extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SharedPreferencesBuilder<String>(
pref: 'access_token',
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
return snapshot.hasData ? Text(snapshot.data) : Container();
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment