代码之家  ›  专栏  ›  技术社区  ›  KhoPhi

飘飘未来归零

  •  0
  • KhoPhi  · 技术社区  · 8 年前

    https://stackoverflow.com/a/49146503/1757321

    遵循解决方案,但在我的情况下不起作用。

    今天下午给我一些启示

      Future<String> loadInterest() async {
        print('Going to load interests');
    
        final whenDone = new Completer();
    
        SharedPreferences prefs = await SharedPreferences.getInstance();
    
        final token = await prefs.getString('token');
    
        print('The token ${token}');
    
        await this.api.interests(token).then((res) {
          // print('The response: ${res['interests']}'); <-- this prints response alright. Data is coming.
          whenDone.complete(res['interests']);
        });
    
        return whenDone.future;
      }
    

    那我就试着用上面的 Future

    new FutureBuilder(
      future: loadInterest(),
      builder: (BuildContext context, snapshot) {
         return snapshot.connectionState == ConnectionState.done
                ? new Wrap(
                     children: InterestChips(snapshot.data),
                  )
                : Center(child: CircularProgressIndicator());
             },
         ),
    

    在哪里? InterestChips(...)

      InterestChips(items) {
        print('Interest Chips ${items}');
        List chipList;
    
        for (Object item in items) {
          chipList.add(Text('${item}'));
        }
    
        return chipList;
      }
    

    但是,我总是 null 作为快照,这意味着 loadInterest() 未来 不会归还任何东西。

    https://stackoverflow.com/a/49146503/1757321

    1 回复  |  直到 7 年前
        1
  •  0
  •   Dan Field    8 年前

    你不需要使用 Completer 为了这个。因为你的方法已经 async ,您应该对第一个代码块执行以下操作:

    Future<String> loadInterest() async {
      print('Going to load interests');
    
      final whenDone = new Completer();
    
      SharedPreferences prefs = await SharedPreferences.getInstance();
    
      final token = await prefs.getString('token');
    
      print('The token ${token}');
    
      final res = await this.api.interests(token).then((res) {
      // print('The response: ${res['interests']}'); <-- this prints response alright. Data is coming.
      return res['interests']);
    }
    

    snapshot.hasError 确保你没有任何例外。