Flutter BLoC 'Future<String>' 不是类型 'String' 的子类型
Flutter BLoC 'Future<String>' is not a subtype of type 'String'
目前我正在尝试以 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)),
],
),
),
这个异常从何而来?我怎样才能防止这种异常?感谢您的帮助!
正如您在评论中提到的,userRepository.getToken()
是一个异步函数,因此 return 值将为 Future。
在 Dart 中,每个带有 async
关键字的函数都将具有 return 值 Future<T>
。
为了获取 Future 的值而不是 Future 本身,提供了两种方法。
then()
- 在异步函数之后调用此函数以获取值。
await
- 在async函数前面加上这个关键字得到值
将您的代码更新为 await userRepository.getToken()
以获得 String
值
目前我正在尝试以 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)),
],
),
),
这个异常从何而来?我怎样才能防止这种异常?感谢您的帮助!
正如您在评论中提到的,userRepository.getToken()
是一个异步函数,因此 return 值将为 Future。
在 Dart 中,每个带有 async
关键字的函数都将具有 return 值 Future<T>
。
为了获取 Future 的值而不是 Future 本身,提供了两种方法。
then()
- 在异步函数之后调用此函数以获取值。await
- 在async函数前面加上这个关键字得到值
将您的代码更新为 await userRepository.getToken()
以获得 String
值