我想在我的 statefulwidget 中构建触发之前获取我的用户 ID。 如果我这样做,那么构建将在我获得我的 ID 之前呈现。如果我将其置于 setstate 中,我的构建将首先使用空字符串,然后使用我的 ID 再次重新呈现它,但这会导致不必要的行为。
那么我该如何解决呢?
String _userid = '';
Future<Null> setUserid() async {
SharedPreferences pref = await SharedPreferences.getInstance();
_userid = pref.getString('FB_USER');
}
initState() {
super.initState();
setUserid();
}
构建
// Widget build
new Flexible(
child: new StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection('users')
.document(_userid)
.collection('rooms')
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return new Text('Loading...');
return new ListView(
children: snapshot.data.documents
.map(
(DocumentSnapshot document) => new Text('lol'),
// )
//new OverviewPresentation(presentation: document),
)
.toList(),
);
},
),
),
最佳答案
你可以使用FutureBuilder
Future<String> setUserid() async {
SharedPreferences pref = await SharedPreferences.getInstance();
_userid = pref.getString('FB_USER');
return _userid;
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: setUserid(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return ... // your widget
} else return CircularProgressIndicator();
});
像这样
关于flutter - 在小部件构建之前获取 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53335797/