我想在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(),
);
},
),
),
答案 0 :(得分:2)
您不能,但是可以防止它为null
。
将StreamBuilder
移至initState
String _userid = '';
dynamic _data;
Future<Null> setUserid() async {
SharedPreferences pref = await SharedPreferences.getInstance();
_userid = pref.getString('FB_USER');
_data = await Firestore.instance
.collection('users')
.document(_userid)
.collection('rooms')
.snapshots().first;
setState(() {});
}
initState() {
super.initState();
setUserid();
}
return new Flexible(
child:
if(_data == null) return new Text('Loading...');
return new ListView(
children: _data.documents
.map(
(DocumentSnapshot document) => new Text('lol'),
// )
//new OverviewPresentation(presentation: document),
)
.toList(),
);
},
),
),
答案 1 :(得分:0)
您可以使用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();
});
类似这样的东西