我正在使用video_player
软件包。我想加载视频。视频数据是来自API的响应。但是我对NoSuchMethodError: The getter 'value' was called on null. Receiver: null Tried calling: value
有错误。我的回答没问题。我print()
的回复中有videoURL。问题是我不知道如何在获得响应后添加video_player
。我曾尝试这样做,但有错误。
这是我的代码:
class _State extends State<MyApps> {
GlobalKey<PaginatorState> paginatorGlobalKey = GlobalKey();
String videoURL;
VideoPlayerController _videoPlayerController;
@override
void initState() {
super.initState();
playVideo(videoURL);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('My Apps'),
),
body: Paginator.listView(
key: paginatorGlobalKey,
pageLoadFuture: sendPagesDataRequest,
pageItemsGetter: listItemsGetterPages,
listItemBuilder: listItemBuilder,
loadingWidgetBuilder: loadingWidgetMaker,
errorWidgetBuilder: errorWidgetMaker,
emptyListWidgetBuilder: emptyListWidgetMaker,
totalItemsGetter: totalPagesGetter,
pageErrorChecker: pageErrorChecker,
scrollPhysics: BouncingScrollPhysics(),
),
);
}
Future<Data> sendPagesDataRequest(int page) async {
try {
String url = Uri.encodeFull("APIURL?page=$page");
http.Response response = await http.get(url);
Data pagesData = pagesDataFromJson(response.body);
return pagesData;
} catch (e) {
}
void playVideo(dynamic item) async {
_videoPlayerController = VideoPlayerController.network(item.videoURL)
..initialize().then((_) {
_videoPlayerController.play();
});
}
Widget listItemBuilder(dynamic item, int index) {
videoURL= item.videoURL;
return InkWell(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
elevation: 4,
margin: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Stack(
children: <Widget>[
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
_videoPlayerController.value.initialized
? AspectRatio(
aspectRatio: _videoPlayerController.value.aspectRatio,
child: VideoPlayer(_videoPlayerController),
)
: Container()
],
),
),
],
),
),
);
}
我的代码中有什么错误,我该如何解决?
答案 0 :(得分:0)
您应将VideoPlayerController.initialize
方法返回的Future存储在State Class变量中:
Future hasInitialized;
void playVideo(dynamic item) async {
_videoPlayerController = VideoPlayerController.network(item.videoURL);
hasInitialized = initialize();
hasInitialized.then((_) {
_videoPlayerController.play();
});
}
然后,您可以使用FutureBuilder class构建窗口小部件,具体取决于未来是否完成。
问题是我不知道如何在获得响应后添加video_player。
此小部件可以通过使用connectionState
或snapshot.hasData
(对于非void Futures)属性来返回Future是否完成的不同事物。
FutureBuilder(
future: hasInitialized,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// Return here what you want to display.
} else {
// Return here what you want to show when the VideoPlayerController is still initializing, like a
// loading spinner.
return Center(child: CircularProgressIndicator());
}
},
)
有关更多信息,请参见official Cookbook.