我正在尝试获取编写在我的 Youtube_player_flutter
文件中的 VideoCard.dart
包的 YouTube 视频链接。现在我将视频的链接作为参数传递给我创建的构造函数,但我得到了 The instance member 'widget' can't be accessed in an initializer.
我认为问题在于使用无状态小部件,但即使将其更改为有状态,问题仍然存在。
class _VideoCardState extends State<VideoCard> {
// static String videoID = 'PQSagzssvUQ';
String videoId = widget.url;
@override
void initState() {
// TODO: implement initState
super.initState();
videoId = widget.url;
}
YoutubePlayerController _controller = YoutubePlayerController(
initialVideoId: videoId,
flags: YoutubePlayerFlags(
autoPlay: true,
mute: false,
),
);
@override
Widget build(BuildContext context) {
return Container(
height: 200,
child: Container(
decoration: BoxDecoration(
color: Color(0xffff8f8f8),
borderRadius: BorderRadius.circular(15),
),
child: YoutubePlayer(
controller: _controller,
liveUIColor: Colors.amber,
showVideoProgressIndicator: true,
),
),
);
}
}
更新 1:
class _VideoCardState extends State<VideoCard> {
String get videoId => widget.url;
// videoId = YoutubePlayer.convertUrlToId(
// "https://www.youtube.com/watch?v=S9bCLPwzSC0")
// .toString();
@override
void initState() {
super.initState();
// print(widget.url);
videoId = widget.url;
}
YoutubePlayerController _controller = YoutubePlayerController(
initialVideoId: videoId, ------------------------> The instance member 'videoId' can't be accessed in an initializer.
flags: YoutubePlayerFlags(
autoPlay: true,
mute: false,
),
);
@override
Widget build(BuildContext context) {
return Container(
height: 200,
child: Container(
decoration: BoxDecoration(
color: Color(0xffff8f8f8),
borderRadius: BorderRadius.circular(15),
),
child: YoutubePlayer(
controller: _controller,
liveUIColor: Colors.amber,
showVideoProgressIndicator: true,
),
),
);
}
}
答案 0 :(得分:0)
您可以尝试使用 getter,类似于以下代码:
class _VideoCardState extends State<VideoCard> {
String get videoId => widget.url;
YoutubePlayerController get _controller => YoutubePlayerController(
initialVideoId: videoId,
flags: YoutubePlayerFlags(
autoPlay: true,
mute: false,
),
);
...
}
答案 1 :(得分:0)
这对我有用:
class _VideoCardState extends State<VideoCard> {
late String videoId;
late YoutubePlayerController _controller;
@override
void initState() {
super.initState();
videoId = YoutubePlayer.convertUrlToId(widget.url).toString();
_controller = YoutubePlayerController(
initialVideoId: videoId,
flags: YoutubePlayerFlags(
autoPlay: false,
mute: false,
),
);
}
@override
Widget build(BuildContext context) {
return Container(
height: 200,
child: Container(
decoration: BoxDecoration(
color: Color(0xffff8f8f8),
borderRadius: BorderRadius.circular(15),
),
child: YoutubePlayer(
controller: _controller,
liveUIColor: Colors.amber,
showVideoProgressIndicator: true,
),
),
);
}
}