Flutter BLoC 'Future<String>' 不是 'String' 型的子类型



当前我正在尝试以BLoC模式从API获取数据。但在通话后,它发出了这样的信息Future不是类型"String"的子类型

这是相关的代码。

Blob

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)),
],
),
),

这个例外从何而来?我该如何防止这种异常情况的发生?谢谢你的帮助!

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

在Dart中,每个具有async关键字的函数都将具有Future<T>的返回值。

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

  1. then()-在异步函数之后调用此函数以获取值
  2. await-在前面添加此关键字并使用async函数获取值

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

相关内容

最新更新