![](/img/trans.png)
[英]Future builder flutter firebase error: A value of type 'Iterable<BlogPost>' can't be assigned to a variable of type 'List<BlogPost>'
[英]Flutter: value of type 'Future<List<UserVideo>>' can't be assigned to a variable of type 'List<UserVideo>'
我正在嘗試使用一個列表(自定義類型)但出現錯誤。
當我嘗試使用 getData() function。 如下所示。
List<UserVideo> videoDataList = [];
videoDataList = UserVideo.getData();
這是 initState 方法。
@override
void initState() {
videoDataList = await UserVideo.getData();
WidgetsBinding.instance.addObserver(this);
_videoListController.init(
_pageController,
videoDataList,
);
super.initState();
}
我收到錯誤消息。
A value of type 'Future<List<UserVideo>>' can't be assigned to a variable of type 'List<UserVideo>'.
Try changing the type of the variable, or casting the right-hand type to 'List<UserVideo>'.
這是 function 的代碼。
class UserVideo {
final String url;
final String image;
final String desc;
UserVideo({
this.url: mockVideo,
this.image: mockImage,
this.desc,
});
Future <List<UserVideo>> getData() async {
List<UserVideo> list = [];
try {
var deviceid = '123';
var dtgUid = '100';
var nodata;
var bodyss = {
"uid": dtgUid,
"deviceid": deviceid,
};
var url = 'http://192.168.100.4:8080/videos/get-data.php';
// Starting Web API Call.
var response = await http
.post(url, body: json.encode(bodyss))
.timeout(Duration(seconds: 5), onTimeout: () {
return null;
});
if (response.statusCode == 200) {
final data = StreamingFromJson(response.body);
if (data.count == null) {
count = 0;
} else {
count = data.count;
}
if (data.content.length > 0 && data.content[0].name != 'Empty') {
for (var i in data.content) {
list.add(UserVideo(image: i.thumbnail, url: i.video, desc: i.title));
}
} else {
nodata = 'No Record Found';
}
print(list.length);
}
} catch (e) {
print("Exception Caught: $e");
}
return list;
}
編輯:
只是顯示工作正常的硬編碼值。
static List<UserVideo> fetchVideo() {
List<UserVideo> list = [];
list.add(UserVideo(image: '', url: mockVideo, desc: 'Test1'));
list.add(UserVideo(image: '', url: mV2, desc: 'MV_TEST_2'));
list.add(UserVideo(image: '', url: mV3, desc: 'MV_TEST_3'));
list.add(UserVideo(image: '', url: mV4, desc: 'MV_TEST_4'));
return list;
}
我可以像這樣使用它並且沒有錯誤。
videoDataList = UserVideo.fetchVideo();
您的方法getData()
返回一個 Future:
Future<List<UserVideo>> getData() async {
List<UserVideo> list = [];
try {
var deviceid = '123';
var dtgUid = '100';
var nodata;
var bodyss = {
"uid": dtgUid,
"deviceid": deviceid,
};
您必須使用async/await
來調用方法getData()
:
List<UserVideo> videoDataList = [];
videoDataList = await UserVideo.getData();
或使用then()
:
List<UserVideo> videoDataList = [];
UserVideo.getData().then((list){
videoDataList = list;
});
注意:要使用await
你需要聲明一個方法async
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.