Before every video whenever I scroll through pageview, I am getting a black screen which I am not sure why it is appearing.

All the videos are playing though

At first, I thought it was due to the internet connection or something, but that does not seem to affect it.

I am getting video URLs from the stream.

Screen:

class _PageViewBuilderState extends State<PageViewBuilder> {
  int _currentPage = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
          stream:
              FirebaseFirestore.instance.collection('Videourls').snapshots(),
          builder: (ctx, snapshot) {
            if (snapshot.hasError) {
              const Center(
                child: Text('Unknown Error'),
              );
            }

            return !snapshot.hasData
                ? const Center(
                    child: CircularProgressIndicator(),
                  )
                : PageView.builder(
                    scrollDirection: Axis.vertical,
                    itemCount: snapshot.data!.docs.length,
                    onPageChanged: (int page) {
                      setState(() {
                        _currentPage = page;
                      });
                    },
                    itemBuilder: (BuildContext context, int index) {
                      return VideoWidget(
                        urlVideo: snapshot.data!.docs[index].get('url'),
                      );
                    },
                  );
          }),
    );
  }
}

class VideoWidget extends StatefulWidget {
  VideoWidget({
    required this.urlVideo,
    Key? key,
  }) : super(key: key);

  final String urlVideo;

  @override
  State<VideoWidget> createState() => _VideoWidgetState();
}

class _VideoWidgetState extends State<VideoWidget> {
  VideoPlayerController? INvideoPlayerController;

  @override
  void initState() {
    super.initState();

    INvideoPlayerController = VideoPlayerController.network(widget.urlVideo)
      ..setLooping(true)
      ..initialize().then((value) => INvideoPlayerController?.play());
  }

  @override
  void dispose() {
    INvideoPlayerController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(alignment: Alignment.center, children: [
      AspectRatio(
        aspectRatio: MediaQuery.of(context).size.width /
            MediaQuery.of(context).size.height,

        child: INvideoPlayerController != null
            ? VideoPlayer(INvideoPlayerController!)
            : Container(),
      ),
      Column(children: [
        SizedBox(
          height: (3 / 4) * MediaQuery.of(context).size.height,
        ),
        Row(children: [
          SizedBox(
            width: (4 / 5) * MediaQuery.of(context).size.width,
          ),
          Column(children: [
            IconButton(
                alignment: Alignment.topCenter,
                iconSize: 30,
                color: Colors.black,
                onPressed: () async {
                  final url = Uri.parse(widget.urlVideo);
                  final response = await http.get(url);
                  final bytes =
                      response.bodyBytes; 

                  final temp = await getTemporaryDirectory();
                  final path = '${temp.path}/video.mp4';
                  File(path)
                      .writeAsBytesSync(bytes); 

                  await Share.shareFiles([path],
                      text: 'Check out this  \n\n');
                },
                icon: const Icon(Icons.share)),
            Text(
              'Share',
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
            )
          ]),
        ]),
      ])
    ]);
  }
}


Solution 1: AmateurCoder

setState() is called everytime the page is changed. Try to remove _currentPage & onPageChanged if it's not used and replace it with a PageController().

For example,

PageView.builder(
    controller: _pageController,
    scrollDirection: Axis.vertical,
    itemCount: snapshot.data!.docs.length,
    itemBuilder: (BuildContext context, int index) {
        return VideoWidget(
        urlVideo: snapshot.data!.docs[index].get('url'),
        );
    },
);

Try to use initState for your stateful widget to set the initial page to 0 everytime a user opens. _currentIndex is used here only for reference, it's not mandatory if not used!

  PageController _pageController;
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _currentIndex = 0;
    _pageController = new PageController(initialPage: _currentIndex);
  }

And don't forget to dispose the controller.

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }