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

future<String>将字符串转换成FutureBuilder和Switch语句

  •  0
  • DolDurma  · 技术社区  · 6 年前

    在我的应用程序中,我有一个简单的方法作为future,它返回 String 作为 Future :

    Future<String> _decodeLessonUrl(BuildContext context) async {
      final ContactData data = await Provider.of<ContactDao>(context).getContacts();
      final String encryptedUrl =
          'encoded string';
      final cryptor = new PlatformStringCryptor();
      try {
        final String decrypted = await cryptor.decrypt(encryptedUrl, '${data.code}');
        return decrypted;
      } on MacMismatchException {
        return null;
      }
    }
    

    我想把未来简单化 String into FutureBuilder Switch 声明:

    FutureBuilder<PlayLessonResponse>(
        future: _myResponse,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              PlayLessonResponse response = snapshot.data;
              switch (response.status) {
                case -1: // payment is ok. show play view
                  final Future<String> decodedLink = _decodeLessonUrl(context);// <-- problem is in this line
                  return PlayerWidget(link:decodedLink);
              }
            }
          }
          return Center(
            child: CircularProgressIndicator( ),
          );
        } ), 
    

    我得到这个错误:

    error: The argument type 'Future<String>' can't be assigned to the parameter type 'String'. 
    

    在那方面我不能用 then 因为这个方法应该返回 Widget

    1 回复  |  直到 6 年前
        1
  •  1
  •   Kalpesh Kundanani    6 年前

    用于转换 Future<String> String 你需要使用FutureBuilder。

    替换为:

    final Future<String> decodedLink = _decodeLessonUrl(context);
    return PlayerWidget(link:decodedLink);
    

    有了这个:

    return FutureBuilder<String>(
        future: _decodeLessonUrl(context);
        builder: (context, snapshot) {
            if(snapshot.hasData){
                return PlayerWidget(link:snapshot.data);
            }else{
                return Center(
                    child: CircularProgressIndicator( ),
                );
            }
        }
    );
    

    我希望这有帮助,如果有任何疑问请评论。 如果这个答案对你有帮助,请接受并投票。