在小部件构建之前获取 SharedPreferences

Syp*_*yph 5 flutter

我想在我的 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();
  }
Run Code Online (Sandbox Code Playgroud)

建造

// 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(),
              );
            },
          ),
        ),
Run Code Online (Sandbox Code Playgroud)

And*_*sky 7

您可以使用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();
  });
Run Code Online (Sandbox Code Playgroud)

像这样的东西