Created
June 20, 2018 20:57
-
-
Save slightfoot/d549282ac0a5466505db8ffa92279d25 to your computer and use it in GitHub Desktop.
SharedPreferencesBuilder thingy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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