1

I am trying to get video from gallery and want to display them in grid view and inside container and then on save button want to upload it to firebase firestore. Firstly, I am not able get the videos from gallery and display it in UI. I have seen many examples and followed them but it is not working for me as I am new into all this and not able to put to it together, where it needs to be..Pls help me out. Thanks in advance.Though the complete code may or may not be related to my query but it may help somebody who is trying to achieve something same. This is the complete code which have play button, video length with indicator. I think I am missing few things here:-

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

}

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

This is where I want display the video:-

   Container(
              height: MediaQuery.of(context).size.height,
              padding: EdgeInsets.all(20),
              child:GridView.builder(
                  itemCount: _video.length,
                  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent: 150,
                    mainAxisSpacing: 10,
                    crossAxisSpacing: 10,
                  ),
                  itemBuilder: (context,index){
                    return Container(
                      child: _controller.value.isInitialized ?
                      Stack(
                         children: [
                          VideoPlayer(_controller),
                          _ControlsOverlay(_controller),

                        ],
                      )
                          :Container(),
                    );
                  }
              ),

            ),

This is where I open gallery and pick video;-

 chooseVideo() async {
final pickedVideo = await picker.getVideo(
    source: ImageSource.gallery,
    maxDuration: const Duration(seconds: 60)
);

setState(() {
  _video.add(File(pickedVideo?.path));
  _controller = VideoPlayerController.file(File(_video.toString()));
});
if (pickedVideo.path == null) retrieveLostData();
  }

 Future<void> retrieveLostData() async {
  final LostData response = await     picker.getLostData();
if (response.isEmpty) {
  return;
}
if (response.file != null) {
  setState(() {
    _video.add(File(response.file.path));
  });
} else {
  print(response.file);
}
 } 

This is complete code:-

class AddVideo extends StatefulWidget {

@override
_AddVideo createState() => _AddVideo();
}

class _AddVideo extends State<AddVideo> {
 bool uploading = false;
double val = 0;
 CollectionReference imgRef;
firebase_storage.Reference ref;

 List<File> _video = [];
 File videoFile;

 List<String> urls = [];
 final picker = ImagePicker();
 final auth = FirebaseAuth.instance;
 final _stoarge = FirebaseStorage.instance;

 VideoPlayerController _controller;


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

 }


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


@override
Widget build(BuildContext context) {
return Scaffold(
  extendBodyBehindAppBar: true,

  appBar: AppBar(
    elevation: 0,
    backgroundColor: Colors.transparent,
    actions: [
      ElevatedButton(
        child: Text("SAVE", style: TextStyle(fontSize: 15)),
        onPressed: () {
          setState(() {
            uploading = true;
          });
          _uploadVideo().whenComplete(() => Navigator.of(context).pop());
        },
        style: ElevatedButton.styleFrom(
            padding: EdgeInsets.fromLTRB(25.0, 15.0, 25.0, 10.0),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(30.0))),
      ),
    ],
  ),

  body: Container(
    child: SafeArea(
      child: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [

           Container(
             // padding: EdgeInsets.all(20),
              child: ElevatedButton(
                child: Text("Open Gallery", style: TextStyle(fontSize: 20)),
                onPressed: () => !uploading ? chooseVideo() : null,
                style: ElevatedButton.styleFrom(
                    padding: EdgeInsets.fromLTRB(25.0, 15.0, 25.0, 10.0),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30.0))),


              ),
            ),

            Container(
              height: MediaQuery.of(context).size.height,
              padding: EdgeInsets.all(20),
              child:GridView.builder(
                  itemCount: _video.length,
                  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent: 150,
                    mainAxisSpacing: 10,
                    crossAxisSpacing: 10,
                  ),
                  itemBuilder: (context,index){
                    return Container(
                      child: _controller.value.isInitialized ?
                      Stack(
                         children: [
                          VideoPlayer(_controller),
                          _ControlsOverlay(_controller),

                        ],
                      )
                          :Container(),
                    );
                  }
              ),

            ),
            uploading ?
            Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      child: Text(
                        'uploading...',
                        style: TextStyle(fontSize: 20),
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    CircularProgressIndicator(
                      value: val,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
                    )
                  ],
                )
            )
                : Container(),
          ],
        ),
      ),
    ),
  ),

  );

  }



  chooseVideo() async {
  final pickedVideo = await picker.getVideo(
    source: ImageSource.gallery,
    maxDuration: const Duration(seconds: 60)
);

setState(() {
  _video.add(File(pickedVideo?.path));
  _controller = VideoPlayerController.file(File(_video.toString()));
});
if (pickedVideo.path == null) retrieveLostData();
 }

 Future<void> retrieveLostData() async {
final LostData response = await picker.getLostData();
if (response.isEmpty) {
  return;
}
if (response.file != null) {
  setState(() {
    _video.add(File(response.file.path));
  });
} else {
  print(response.file);
}
 }

 _uploadVideo() async {
for (var video in _video) {
  var _ref = _stoarge.ref().child("videos/" + Path.basename(video.path));
  await _ref.putFile(video);
  String url = await _ref.getDownloadURL();

  print(url);
  urls.add(url);
  print(url);
}
print("uploading:" + urls.asMap().toString());
await FirebaseFirestore.instance
    .collection("users")
    .doc(auth.currentUser.uid)
    .update({"images": urls});
//  .doc(auth.currentUser.uid).update({"images": FieldValue.arrayUnion(urls) });
   }

 }

 class _ControlsOverlay extends StatelessWidget {
 String getPosition() {
   final duration = Duration(
      milliseconds: controller.value.position.inMilliseconds.round());

  return [duration.inMinutes, duration.inSeconds]
    .map((seg) => seg.remainder(60).toString().padLeft(2, '0'))
    .join(':');
 }

 const _ControlsOverlay(this.controller);

final VideoPlayerController controller;

  @override
 Widget build(BuildContext context) {
return Stack(
  children: <Widget>[
    AnimatedSwitcher(
      duration: Duration(milliseconds: 50),
      reverseDuration: Duration(milliseconds: 200),
      child: controller.value.isPlaying
          ? SizedBox.shrink()
          : Container(
        color: Colors.black26,
        child: Center(
          child: Icon(
            Icons.play_arrow,
            color: Colors.white,
            size: 100.0,
          ),
        ),
      ),
    ),
    GestureDetector(
      onTap: () {
        controller.value.isPlaying ? controller.pause() : controller.play();
      },
    ),
    Positioned(
        bottom: 0,
        left: 0,
        right: 0,
        child: Row(
          children: [
            const SizedBox(width: 8),
            Expanded(child: Text(getPosition()),),
            const SizedBox(width: 8),
            Expanded(child: buildIndicator()),
            const SizedBox(width: 8),

          ],
        )
    ),

  ],
);
  }

 Widget buildIndicator() => Container(
margin: EdgeInsets.all(8).copyWith(right: 0),
height: 10,
child: VideoProgressIndicator(
  controller, allowScrubbing: true,
),
  );

 }   
GAGAN SINGH
  • 261
  • 2
  • 17

0 Answers0