【问题标题】:Flutter BLoC 'Future<String>' is not a subtype of type 'String'Flutter BLoC 'Future<String>' 不是'String' 类型的子类型
【发布时间】:2021-07-18 10:43:13
【问题描述】:

目前我正在尝试以 BLoC 模式从 API 获取数据。但是在通话之后,它会抛出这个消息。 'Future' 不是 'String' 类型的子类型

这里是相关代码。

集团

Stream<NewsState> mapEventToState(NewsEvent event) async* {
    if (event is FetchNews) {
      yield event.isFeatured == true
          ? NewsFeaturedLoading()
          : NewsCommonLoading();

      try {
        print("http req->" + event.isFeatured.toString());
        final List<News> newsList =
            await _fetchNews(event.isFeatured, userRepository.getToken());

        yield event.isFeatured == true
            ? NewsFeaturedSuccess(newsList: newsList)
            : NewsCommonSuccess(newsList: newsList);
      } catch (error) {
        print(error);
        yield event.isFeatured == true
            ? NewsFeaturedFailure(error: error.toString())
            : NewsCommonFailure(error: error.toString());
      }
    }
  }
}

HttpCall

Future<List<News>> _fetchNews(isFeatured, accessToken) async {
  print("before httprequest->>" + accessToken);
  final http.Response response = await http.post(
    Uri.parse(Constant.baseUrl + "/api/news"),
    headers: {
      'Content-type': 'application/json',
      'Accept': 'application/json',
      "x-access-token": "Bearer " + accessToken,
    },
    body: {
      "isFeatured": isFeatured,
    },
  );

  print("response->>>>" + response.body);
  if (response.statusCode == 200) {
    print("news-> " + response.body);
    var obj = json.decode(response.body);
    final data = obj["data"] as List;
    return data.map((rawPost) {
      return News(
        id: rawPost['_id'],
        title: rawPost['Title'],
        content: rawPost['Description'],
      );
    }).toList();
  } else {
    throw Exception(json.decode(response.body));
  }
}

查看

SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: Column(
                children: <Widget>[
                  SizedBox(height: 25.0),
                  Align(
                    alignment: Alignment.topLeft,
                    child: Padding(
                      padding: EdgeInsets.only(left: 19.0),
                      child: Text("Common news",
                          style: Constant.newsCommonTextStyle),
                    ),
                  ),
                  if (state is NewsCommonLoading) CircularProgressIndicator(),
                  if (state is NewsCommonSuccess) CommonNews(),
                  if (state is NewsCommonFailure)
                    Text(state.error, style: TextStyle(color: Colors.red)),
                ],
              ),
            ),

这个异常是从哪里来的?我该如何防止这种异常?感谢您的帮助!

【问题讨论】:

  • 您能否更新问题以引导我找到确切发生此错误的区域?
  • 最终列表 newsList = await _fetchNews(event.isFeatured, userRepository.getToken());在这一行,抛出异常。
  • userRepository.getToken() 是异步函数吗?
  • 是的。它正在使用异步
  • @RohanThacker thx 伙计,我想通了。

标签: flutter bloc


【解决方案1】:

正如您在评论中提到的 userRepository.getToken() 是一个异步函数,因此返回值将是 Future。

在 Dart 中,每个带有 async 关键字的函数的返回值都是 Future&lt;T&gt;

为了获取 Future 的值而不是 Future 本身,提供了两种方法。

  1. then() - 在异步函数之后调用此函数以获取值。
  2. await - 在前面加上这个关键字和异步函数来获取值

将您的代码更新为 await userRepository.getToken() 以获得 String

【讨论】:

  • 我能再问一件事吗?
  • 我有一个名为“新闻”的主要集团。我正在尝试并行触发两个事件(FeaturedNews,CommonNews),我将它们添加为“ return NewsBloc(userRepository: userRepository)..add(FetchNews(isFeatured: true)) ..add(FetchNews(isFeatured: false) );"。但只有最后一个正在执行。我怎样才能完成第一个活动?
  • 对不起,我不使用 BloC,我不知道您如何解决评论中的问题
  • @ARLEQUINA 触发 1 个事件,作为 FeaturedNews 和 CommonNews 的通用事件,并且在逻辑产生 2 个状态后的集团中。 1 为 FeaturedNews,第 2 为 CommonNews。
  • 我已经想通了。谢谢您的帮助!真诚的。
猜你喜欢
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 2019-08-04
  • 2021-07-10
  • 2021-08-10
  • 2018-09-28
  • 2019-06-26
相关资源
最近更新 更多