Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

List of video players #9

Closed
veselin1v opened this issue Feb 15, 2018 · 15 comments
Closed

List of video players #9

veselin1v opened this issue Feb 15, 2018 · 15 comments

Comments

@veselin1v
Copy link

Is there easy way to make list of video players? I want to show up more than 1 video. I tried this:

void main() {
  runApp(
    new ChewieDemo(controller:[
       new VideoPlayerController('https://flutter.github.io/assets-for-api-docs/videos/butterfly.mp4'),
       new VideoPlayerController('https://flutter.github.io/assets-for-api-docs/videos/bee.mp4'),
    ]),
  );
}

class ChewieDemo extends StatefulWidget {
  final String title;
  final List <VideoPlayerController> controller;

But widget.controller gives error with argument type List. Could you help me?

@brianegan
Copy link
Collaborator

brianegan commented Feb 15, 2018

Hey @vessivanov, sure thing!

tl;dr -- you need to create a ListView of Chewie widgets.

ChewieDemo is just a custom Widget I've written for the Example App. To create a Video player, you need to use new Chewie(controller).

The problem you're running into: If you change a single VideoPlayerController into a List<VideoPlayerController>, you also need to change the _ChewieDemoState class' build method, because it is designed to output a single video from a single controller.

You can convert the List<VideoPlayerController> into a List<Widget>, and pass that list to a ListView Widget.

Example below:

import 'package:chewie/chewie.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(
    new ChewieDemo(
      controllers: [
        new VideoPlayerController(
          'https://flutter.github.io/assets-for-api-docs/videos/butterfly.mp4',
        ),
        new VideoPlayerController(
          'https://flutter.github.io/assets-for-api-docs/videos/bee.mp4',
        )
      ],
    ),
  );
}

class ChewieDemo extends StatefulWidget {
  final String title;
  final List<VideoPlayerController> controllers;

  ChewieDemo({this.title = 'Chewie Demo', this.controllers});

  @override
  State<StatefulWidget> createState() {
    return new _ChewieDemoState();
  }
}

class _ChewieDemoState extends State<ChewieDemo> {
  TargetPlatform _platform;

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: widget.title,
      theme: new ThemeData.light().copyWith(
        platform: _platform ?? Theme.of(context).platform,
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text(widget.title),
        ),
        // Create a ListView of Chewie Players
        body: new ListView(
          // Here's the magic. We convert our List<VideoPlayerController>
          // into a List<Widget>.
          children: widget.controllers.map((controller) {
            return new Container(
              margin: new EdgeInsets.symmetric(vertical: 20.0),
              // To display a single Video Player, you need to create a `Chewie` Widget.
              // Since we want to show multiple videos, each item in the List will
              // contain a Chewie player
              child: new Chewie(
                controller,
                aspectRatio: 3 / 2,
                autoPlay: true,
                looping: true,
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

@veselin1v
Copy link
Author

@brianegan You are great! Thank you very much!

@brianegan
Copy link
Collaborator

Sure thing! Let me know if I can help in any other way :)

@veselin1v
Copy link
Author

Hello again!

I am a beginner with a flutter and I have one more question. How can I add other items above or below a video. For example, I want to add a card above any video with some information.

Do I need to add a final List cards; in the ChewieDemo class and to loop the whole class? I don't understand how to make a few elements in the home and body key. Can I add a new children with card in ListView?

I added this code

new Card(
  child: new Column(
    mainAxisSize: MainAxisSize.min,
    children: <Widget>[
      const ListTile(
        leading: const Icon(Icons.album),
        title: const Text('The Enchanted Nightingale'),
        subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
      ),
      new ButtonTheme.bar( // make buttons use the appropriate styles for cards
        child: new ButtonBar(
          children: <Widget>[
            new FlatButton(
              child: const Text('BUY TICKETS'),
              onPressed: () { /* ... */ },
            ),
            new FlatButton(
              child: const Text('LISTEN'),
              onPressed: () { /* ... */ },
            ),
          ],
        ),
      ),
    ],
  ),
)

instead ListView and works, but I want both things

I'm sorry if I'm cheeky, it's just hard to figure out.

@brianegan
Copy link
Collaborator

brianegan commented Feb 16, 2018

Hey hey, not cheeky at all! No worries if you're starting out and need help :)

What you need to do is create a new Class that holds the information you need, then loop over that to create Widgets that contain a Card and a Chewie player. For example:

class VideoItem {
  final String title;
  final String description;
  final VideoController controller;

  VideoItem(this.title, this.description, this.controller);
}

You then need to create a List of these items, like so:

final List<VideoItem> items = [
  new VideoItem(
    'The Enchanted Nightingale',
    'Music by Julie Gable. Lyrics by Sidney Stein.',
    new VideoPlayerController('some url here'),
  ),
  new VideoItem(
    'Second item',
    'Second description',
    new VideoPlayerController('some other url here'),
  ),
];

You then need to convert this List<VideoItem> into a List<Widget> just like we did the first time.

Since you want a Card above the Chewie Widget, you'll need to wrap the Card and Chewie Widgets in a Column Widget, just like you've got in your example

@veselin1v
Copy link
Author

veselin1v commented Feb 16, 2018 via email

@veselin1v
Copy link
Author

I tried to do it, but something shines in red. Can you write me a complete example of a list of items that contain a card and a video player.

I tried something like this:

import 'package:chewie/chewie.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(
    //here ??
  );
}

class VideoItem extends StatefulWidget {
  final String title;
  final String description;
  final VideoPlayerController controller;

  VideoItem({this.title, this.description, this.controller});
  
  final List<VideoItem> items = [
    new VideoItem(
      'The Enchanted Nightingale',
      'Music by Julie Gable. Lyrics by Sidney Stein.',
      new VideoPlayerController('some url here'),
    ),
    new VideoItem(
      'Second item',
      'Second description',
      new VideoPlayerController('some other url here'),
    ),
  ];
  
  @override
  State<StatefulWidget> createState() {
    return new _VideoItemState();
  }
}

class _VideoItemState extends State<VideoItem> {
  TargetPlatform _platform;

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: widget.title,
      theme: new ThemeData.light().copyWith(
        platform: _platform ?? Theme.of(context).platform,
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text(widget.title),
        ),
        // Create a ListView of Chewie Players
        body: new ListView(
          // Here's the magic. We convert our List<VideoPlayerController>
          // into a List<Widget>.
          children: widget.items.map((controller) {
            return new Container(
              margin: new EdgeInsets.symmetric(vertical: 20.0),
              // To display a single Video Player, you need to create a `Chewie` Widget.
              // Since we want to show multiple videos, each item in the List will
              // contain a Chewie player
              child: new Chewie(
                controller,
                aspectRatio: 3 / 2,
                autoPlay: false,
                autoInitialize: true,
                looping: true,
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

@brianegan
Copy link
Collaborator

Yo yo, so here's a quick working example of what you're trying to do: It doesn't look great, but demonstrates the technique of:

  1. Create a new VideoItem class -- not a Widget, just a data definition
  2. Create a List<VideoItem> and pass that to your Widget
  3. Convert the List<VideoItem> into a List<Widget> and pass that to a ListView Widget.
import 'package:chewie/chewie.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(
    new ChewieDemo(
      items: [
        new VideoItem(
          title: 'Fluttering Butterfly',
          description: 'A lovely butterfly flapping it\'s wings',
          controller: new VideoPlayerController(
            'https://flutter.github.io/assets-for-api-docs/videos/butterfly.mp4',
          ),
        ),
        new VideoItem(
          title: 'Beeeeeeeees!',
          description: 'Silly little bee',
          controller: new VideoPlayerController(
            'https://flutter.github.io/assets-for-api-docs/videos/bee.mp4',
          ),
        )
      ],
    ),
  );
}

class VideoItem {
  final String title;
  final String description;
  final VideoPlayerController controller;

  VideoItem({this.title, this.description, this.controller});
}

class ChewieDemo extends StatefulWidget {
  final String title;
  final List<VideoItem> items;

  ChewieDemo({this.title = 'Chewie Demo', this.items});

  @override
  State<StatefulWidget> createState() {
    return new _ChewieDemoState();
  }
}

class _ChewieDemoState extends State<ChewieDemo> {
  TargetPlatform _platform;

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: widget.title,
      theme: new ThemeData.light().copyWith(
        platform: _platform ?? Theme.of(context).platform,
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text(widget.title),
        ),
        body: new ListView(
          children: widget.items.map((item) {
            return new Container(
              margin: new EdgeInsets.only(bottom: 20.0),
              child: new Card(
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    new Text(
                      item.title,
                      style: Theme.of(context).textTheme.title,
                    ),
                    new Text(
                      item.description,
                      style: Theme.of(context).textTheme.subhead,
                    ),
                    new Chewie(
                      item.controller,
                      aspectRatio: 3 / 2,
                      autoPlay: true,
                      looping: true,
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

@veselin1v
Copy link
Author

That's exactly what I needed. Now it's more clear to understand. Thank you so much!!!

@veselin1v
Copy link
Author

veselin1v commented Feb 22, 2018

Hi, Brain! Everything was fine, but today when I ran the app, I've got an exception:


vesko@vesko-Lenovo-E50-00:~/Documents/chewie-master/example$ flutter run
Launching lib/main.dart on SM A310F in debug mode...
Initializing gradle...                                5.4s
Resolving dependencies...                            12.8s
Running 'gradlew assembleDebug'...                   58.0s
Built build/app/outputs/apk/debug/app-debug.apk (25.4MB).
Installing build/app/outputs/apk/app.apk...          74.8s
I/FlutterActivityDelegate(28268): onResume setting current activity to this
Syncing files to device SM A310F...                       
I/MediaPlayer(28268): Need to enable context aware info
V/MediaPlayer-JNI(28268): native_setup
V/MediaPlayer(28268): constructor
V/MediaPlayer(28268): setListener
V/MediaPlayer(28268): setVideoSurfaceTexture
V/MediaPlayer-JNI(28268): setParameter: key 1400
V/MediaPlayer(28268): MediaPlayer::setParameter(1400)
V/MediaPlayer-JNI(28268): setAudioStreamType: 3
V/MediaPlayer(28268): MediaPlayer::setAudioStreamType
V/MediaPlayer(28268): setVideoSurfaceTexture
V/MediaPlayer(28268): prepareAsync
V/MediaPlayer-JNI(28268): native_setup
V/MediaPlayer(28268): constructor
V/MediaPlayer(28268): setListener
V/MediaPlayer(28268): setVideoSurfaceTexture
V/MediaPlayer-JNI(28268): setParameter: key 1400
V/MediaPlayer(28268): MediaPlayer::setParameter(1400)
D/MediaHTTPConnection(28268): setReadTimeOut =  30000ms
V/MediaPlayer-JNI(28268): setAudioStreamType: 3
V/MediaPlayer(28268): MediaPlayer::setAudioStreamType
V/MediaPlayer(28268): setVideoSurfaceTexture
V/MediaPlayer(28268): prepareAsync
D/MediaHTTPConnection(28268): setReadTimeOut =  30000ms
D/NetworkSecurityConfig(28268): No Network Security Config specified, using platform default
D/MediaHTTPConnection(28268): setReadTimeout with 30000ms
D/MediaHTTPConnection(28268): setReadTimeout with 30000ms
I/System.out(28268): (HTTPLog)-Static: isSBSettingEnabled false
I/System.out(28268): (HTTPLog)-Static: isSBSettingEnabled false
I/System.out(28268): (HTTPLog)-Static: isSBSettingEnabled false
I/System.out(28268): (HTTPLog)-Static: isSBSettingEnabled false
I/MediaHTTPConnection(28268): response code = 200
V/MediaHTTPConnection(28268): mTotalSize is 1293015
I/MediaHTTPConnection(28268): response code = 200
V/MediaHTTPConnection(28268): mTotalSize is 2429896
V/MediaPlayer(28268): message received msg=200, ext1=701, ext2=0
W/MediaPlayer(28268): info/warning (701, 0)
V/MediaPlayer(28268): callback application
V/MediaPlayer(28268): back from callback
V/MediaPlayer(28268): message received msg=200, ext1=701, ext2=0
W/MediaPlayer(28268): info/warning (701, 0)
V/MediaPlayer(28268): callback application
V/MediaPlayer(28268): back from callback
V/MediaPlayer-JNI(28268): getCurrentPosition: 0 (msec)
V/MediaPlayer-JNI(28268): getCurrentPosition: 0 (msec)
V/MediaPlayer(28268): message received msg=3, ext1=0, ext2=0
V/MediaPlayer(28268): buffering 0
V/MediaPlayer(28268): callback application
V/MediaPlayer(28268): back from callback
V/MediaPlayer(28268): message received msg=3, ext1=0, ext2=0
V/MediaPlayer(28268): buffering 0
V/MediaPlayer(28268): callback application
V/MediaPlayer(28268): back from callback
V/MediaPlayer(28268): message received msg=3, ext1=0, ext2=0
V/MediaPlayer(28268): buffering 0
V/MediaPlayer(28268): callback application

and video players didn't work. Could you help me?

Also:

I/FlutterActivityDelegate(25677): onResume setting current activity to this
I/hwaps   (25677): JNI_OnLoad
E/flutter (25677): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (25677): setState() called after dispose(): _MaterialControlsState#10d5e(lifecycle state: defunct, not mounted)
E/flutter (25677): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter (25677): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter (25677): #0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1090)
E/flutter (25677): #1      State.setState (package:flutter/src/widgets/framework.dart:1107)
E/flutter (25677): #2      _MaterialControlsState._initialize.<anonymous closure> (package:chewie/src/material_controls.dart:252)
E/flutter (25677): #3      Timer._createTimer.<anonymous closure> (dart:async-patch/dart:async/timer_patch.dart:21)
E/flutter (25677): #4      _Timer._runTimers (dart:isolate-patch/dart:isolate/timer_impl.dart:382)
E/flutter (25677): #5      _Timer._handleMessage (dart:isolate-patch/dart:isolate/timer_impl.dart:416)
E/flutter (25677): #6      _RawReceivePortImpl._handleMessage (dart:isolate-patch/dart:isolate/isolate_patch.dart:165)

@brianegan
Copy link
Collaborator

brianegan commented Feb 22, 2018

Thanks! A bit busy these next couple days, but I'll take a look when I have time :)

@Chimba123
Copy link

@brianegan thanks for the chewie plugin. I wanted to find out would you be in a position to know how to implement a picture/video frame that shows as the face cover of the video e.g. the way YouTube does it. All videos have a picture/cover which disappears after you click the video and it starts playing.
The video player plugin/Chewie chooses the first frame which is usually just a black image, that doesn't look nice. I wanted to be able to choose a frame/picture with some clear image to display as the cover of the video which should then fade out after a user taps on the video and it starts playing.

@cbenhagen
Copy link
Collaborator

You can use the placeholder option to achieve this.

PS.: Please open new issues instead of hijacking old ones.

@svaldespinogut
Copy link

Se puede realizar con chewie una reporduccion de un video con un slider?

@parth22
Copy link

parth22 commented Mar 28, 2020

Hello @brianegan Can i make this type of list with update and delete functionality if my url comes from a server api and also my list is dynamic i mean the number of video url if yes then it will help-full for me. i try below code list is working perfect but when i try to delete or update action my list will not updated.

class WatchMee extends StatefulWidget {
  @override
  _WatchMeeState createState() => _WatchMeeState();
}

class _WatchMeeState extends State<WatchMee> {
  FlagBlog flagBlog = FlagBlog();
  Timer _timer;
  // List<VideoPlayerController> listOfVideos = [];
  // VideoPlayerController _controller;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    updateWatchMeeData();
  }
  @override
  void initState() {
    allWatchmee = [];
    flagBlog.widgetFlagProcess(true);
    Future.delayed(Duration(seconds: 1), () {
      flagBlog.widgetFlagProcess(false);
    });
    prefrenceObjects.getString(SharedPreferenceKeys.USER_WATCHMEE_DATA) != null
        ? allWatchmee = json.decode(
            prefrenceObjects.getString(SharedPreferenceKeys.USER_WATCHMEE_DATA))
        : print('Nothing found');
    super.initState();
  }

  @override
  void dispose() {
    // _controller.dispose();
    // for (int i = 0; i < allWatchmee.length; i++) {
    //   listOfVideos[i].dispose();
    // }
    super.dispose();
  }

  updateWatchMeeData() {
    watchmeeBloc.fetchAllWatchmee = BehaviorSubject<ApiResponseModel>();
    watchmeeBloc.listAllWatchmee();
    watchmeeBloc.getAllWatchMee.listen((onData) {
      if (onData.status == 200) {
        List<dynamic> picmee = onData.data.watchmeeModel;
        if (picmee != allWatchmee) {

          prefrenceObjects.setString(
              SharedPreferenceKeys.USER_WATCHMEE_DATA, json.encode(picmee));
          allWatchmee = json.decode(prefrenceObjects
              .getString(SharedPreferenceKeys.USER_WATCHMEE_DATA));
          // for (int i = 0; i < allWatchmee.length; i++) {
          //   listOfVideos
          //       .add(new VideoPlayerController.network(allWatchmee[i]['file']));
          //   listOfVideos[i].initialize().then((_) {
          if (mounted) {
            setState(() {});
          }
          //   });
          // }
        }
      }
    });
  }

  Future<Null> refreshList() async {
    await Future.delayed(Duration(seconds: 2));
    // picmeeBloc.allWatchmeeList();
    updateWatchMeeData();
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => false,
      child: Scaffold(
        body: StreamBuilder<bool>(
            stream: flagBlog.widgetFlag,
            builder: (context, snapshot) {
              return snapshot.data == true
                  ? Center(
                      child: CircularProgressIndicator(
                        valueColor: new AlwaysStoppedAnimation<Color>(
                            AppTheme.colors.primaryBlue),
                      ),
                    )
                  : listItems(context);
            }),
      ),
    );
  }

  Widget listItems(BuildContext context) {
    return allWatchmee.length != 0
        ? RefreshIndicator(
            color: AppTheme.colors.primaryBlue,
            onRefresh: refreshList,
            child: ListView.builder(
              itemCount: allWatchmee.length,
              cacheExtent: 1000,
              addAutomaticKeepAlives: true,
              itemBuilder: (BuildContext context, int index) {
                // listOfVideos.add(
                //     VideoPlayerController.network(allWatchmee[index]["file"])
                //       ..initialize().then((_) {}));
                DateFormat dtf = DateFormat("MM/dd/yy hh:mm:ss a");
                DateTime date = dtf.parse(allWatchmee[index]['dateCreated']);
                DateTime utcDate = DateTime.utc(date.year + 2000, date.month,
                    date.day, date.hour, date.minute, date.second);
                DateFormat dtfTwo = DateFormat("MMM, dd yyyy hh:mm:ss a");
                String dateTwo = dtfTwo.format(utcDate);
                // String edate = utcDate.toLocal().toString();
                DateTime utcPlusDate = utcDate.add(Duration(hours: 36));
                int likeMinute = allWatchmee[index]['likeMin'] == null
                    ? 0
                    : allWatchmee[index]['likeMin'];
                int disLikeMinute = allWatchmee[index]['disLikeMin'] == null
                    ? 0
                    : allWatchmee[index]['disLikeMin'];
                DateTime newUtcPlusDate = likeMinute == 0 && disLikeMinute == 0
                    ? utcPlusDate
                    : utcPlusDate.add(Duration(minutes: likeMinute));
                DateTime fUtcSubDate = likeMinute == 0 && disLikeMinute == 0
                    ? newUtcPlusDate
                    : newUtcPlusDate.subtract(Duration(minutes: disLikeMinute));
                DateTime currentDate = DateTime.now().toLocal();
                DateTime toLocalC = utcDate.toLocal();
                var different = currentDate.difference(toLocalC);
                String postCre = different.inDays > 365
                    ? "${(different.inDays / 365).floor()} ${(different.inDays / 365).floor() == 1 ? "year" : "years"} ago"
                    : different.inDays > 30
                        ? "${(different.inDays / 30).floor()} ${(different.inDays / 30).floor() == 1 ? "month" : "months"} ago"
                        : different.inDays > 7
                            ? "${(different.inDays / 7).floor()} ${(different.inDays / 7).floor() == 1 ? "week" : "weeks"} ago"
                            : different.inDays > 0
                                ? "${different.inDays} ${different.inDays == 1 ? "day" : "days"} ago"
                                : different.inHours > 0
                                    ? "${different.inHours} ${different.inHours == 1 ? "hour" : "hours"} ago"
                                    : different.inMinutes > 0
                                        ? "${different.inMinutes} ${different.inMinutes == 1 ? "minute" : "minutes"} ago"
                                        : different.inMinutes == 0
                                            ? "Just Now"
                                            : "";
                var hour = fUtcSubDate.difference(currentDate).inHours;
                var minute =
                    fUtcSubDate.difference(currentDate).inMinutes - (hour * 60);
                return Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Container(
                            height: 40,
                            width: 40,
                            margin:
                                EdgeInsets.only(right: 10.0, left: 20, top: 10),
                            child: allWatchmee == null
                                ? ClipOval(
                                    child: Image.asset('images/fakeDP.png'),
                                  )
                                : allWatchmee[index]['user']['avatar'] == null
                                    ? ClipOval(
                                        child: Image.asset('images/fakeDP.png'),
                                      )
                                    : ClipOval(
                                        child: CachedNetworkImage(
                                          imageUrl: picmeeImageUrl +
                                              allWatchmee[index]['user']
                                                  ['avatar'] +
                                              '.jpg',
                                          placeholder: (context, url) => Center(
                                            child: Center(
                                              child: Container(
                                                height: 20,
                                                width: 20,
                                                child:
                                                    CircularProgressIndicator(
                                                  strokeWidth: 2,
                                                  valueColor:
                                                      new AlwaysStoppedAnimation<
                                                              Color>(
                                                          AppTheme.colors
                                                              .primaryBlue),
                                                ),
                                              ),
                                            ),
                                          ),
                                          fit: BoxFit.cover,
                                        ),
                                      ),
                          ),
                          GestureDetector(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Container(
                                  margin: EdgeInsets.only(top: 10),
                                  child: Text(
                                    '${allWatchmee[index]['user']['firstName']} ${allWatchmee[index]['user']['lastName']}',
                                    style: TextStyle(
                                      fontFamily: 'SFUIText_Medium',
                                      color: Colors.black,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 14,
                                    ),
                                  ),
                                ),
                                Text(
                                  postCre,
                                  style: TextStyle(
                                    fontFamily: 'SFUIText_Regular',
                                    color: Colors.grey,
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                            onTap: () {
                              int testId = allWatchmee[index]['user']['id'];
                              AppRoutes.showLoader(context);
                              searchUserBloc.fetcher =
                                  BehaviorSubject<ApiResponseModel>();
                              searchUserBloc.searchUserSink();
                              searchUserBloc.allData.listen((onData) {
                                if (onData.status == 200) {
                                  SearchModel userdata;
                                  List<SearchModel> searchList =
                                      onData.data.searchData;
                                  searchList.forEach((f) => f.id == testId
                                      ? userdata = f
                                      : print('Not compare'));
                                  friendVisitId = userdata.id;
                                  statusC = userdata.connectionStatus;
                                  statusC == null || statusC == 0
                                      ? btnName = 'Connect'
                                      : statusC == 1
                                          ? btnName = 'Pending'
                                          : statusC == 2
                                              ? btnName = 'Respond'
                                              : btnName = 'Connected';
                                  // AppRoutes.showLoader(context);
                                  myPicmeeBloc.allFriendPicmeeList();
                                  friendConnectionBloc.getFrindConnection();
                                  myBlogmeeBloc.allFriendBlogmeeList();
                                  _timer = new Timer(
                                      const Duration(
                                          seconds: 1, milliseconds: 500), () {
                                    AppRoutes.dismissLoader(context);
                                    friendProfileBloc.userProfileController =
                                        BehaviorSubject<ApiResponseModel>();
                                    friendVisitId == currentUser
                                        ? AppRoutes.goto(
                                            context,
                                            MainScreen(
                                              friNo: testId,
                                              conNo: testId.toString() ==
                                                      currentUserId
                                                  ? currentUserId
                                                  : 3,
                                            ))
                                        : statusC == null || statusC == 1
                                            ? AppRoutes.goto(
                                                context, FriendProfile())
                                            : AppRoutes.goto(
                                                context, FriendProfileTwo());
                                  });
                                }
                              });
                            },
                          ),
                          Spacer(),
                          Container(
                            margin: EdgeInsets.only(top: 10),
                            child: IconButton(
                              icon: Icon(Icons.more_vert),
                              onPressed: () {
                                containerForSheet<String>(
                                  context: context,
                                  child: CupertinoActionSheet(
                                    actions: <Widget>[
                                      allWatchmee[index]['user']['id'] ==
                                              currentUser
                                          ? Container()
                                          : CupertinoActionSheetAction(
                                              child: const Text(
                                                "Block this user",
                                                style: TextStyle(
                                                  fontFamily:
                                                      'SFUIText_Regular',
                                                  color: Colors.red,
                                                ),
                                              ),
                                              onPressed: () async {
                                                AlertBoxTwo().show(
                                                    context,
                                                    'Alert',
                                                    'Are you sure you want to block this user ?',
                                                    'Cancel',
                                                    (value) {
                                                      Navigator.of(context)
                                                          .popUntil((route) =>
                                                              route.isFirst);
                                                    },
                                                    'OK',
                                                    (value) {
                                                      AppRoutes.showLoader(
                                                          context);
                                                      connectionBloc.fetcher =
                                                          BehaviorSubject<
                                                              ApiResponseModel>();
                                                      connectionBloc
                                                          .blockeUserRequest(int
                                                              .parse(allWatchmee[
                                                                          index]
                                                                      [
                                                                      'user']["id"]
                                                                  .toString()));
                                                      connectionBloc
                                                          .allDataFetcher
                                                          .listen(
                                                              (onData) async {
                                                        if (onData.status ==
                                                            200) {
                                                          updateWatchMeeData();
                                                          AppRoutes
                                                              .dismissLoader(
                                                                  context);
                                                          int userId =
                                                              allWatchmee[index]
                                                                      ['user']
                                                                  ['id'];
                                                          Navigator.of(context)
                                                              .popUntil((route) =>
                                                                  route
                                                                      .isFirst);
                                                          final snackBar =
                                                              SnackBar(
                                                            content: Text(
                                                              "User successfully blocked",
                                                              style:
                                                                  snackBarText,
                                                            ),
                                                            duration: Duration(
                                                                milliseconds:
                                                                    1800),
                                                          );
                                                          Scaffold.of(context)
                                                              .showSnackBar(
                                                                  snackBar);
                                                          deleteFriendRequest(
                                                              userId);
                                                        } else {
                                                          AppRoutes
                                                              .dismissLoader(
                                                                  context);
                                                          Navigator.of(context)
                                                              .popUntil((route) =>
                                                                  route
                                                                      .isFirst);
                                                          final snackBar =
                                                              SnackBar(
                                                            content: Text(
                                                              "Something wrong",
                                                              style:
                                                                  snackBarText,
                                                            ),
                                                            duration: Duration(
                                                                milliseconds:
                                                                    1800),
                                                          );
                                                          Scaffold.of(context)
                                                              .showSnackBar(
                                                                  snackBar);
                                                        }
                                                      });
                                                    });
                                              },
                                            ),
                                      allWatchmee[index]['user']['id'] ==
                                              currentUser
                                          ? Container()
                                          : CupertinoActionSheetAction(
                                              child: const Text(
                                                "Report",
                                                style: TextStyle(
                                                  fontFamily:
                                                      'SFUIText_Regular',
                                                  color: Colors.red,
                                                ),
                                              ),
                                              onPressed: () async {
                                                setState(() {
                                                  AppRoutes.showLoader(context);
                                                });
                                                var file =
                                                    await DefaultCacheManager()
                                                        .getSingleFile(
                                                            "$picmeeImageUrl${allWatchmee[index]['file']}");
                                                final Email email = Email(
                                                  recipients: [
                                                    'itsmeeinfo@gmail.com'
                                                  ],
                                                  subject:
                                                      'Report of the Watchmee Post',
                                                  body:
                                                      'User Name: ${allWatchmee[index]['user']['firsName']} ${allWatchmee[index]['user']['lastName']}\nPost Date&Time: $dateTwo (UTC)\nPostTitle: ${allWatchmee[index]['text']}',
                                                  // 'No data',
                                                  attachmentPath: file.path,
                                                  isHTML: false,
                                                );
                                                await FlutterEmailSender.send(
                                                    email);
                                                setState(() {
                                                  AppRoutes.dismissLoader(
                                                      context);
                                                });
                                                Navigator.of(context).pop();
                                              },
                                            ),
                                      allWatchmee[index]['user']['id'] ==
                                              currentUser
                                          ? CupertinoActionSheetAction(
                                              child: const Text(
                                                "Delete",
                                                style: TextStyle(
                                                  fontFamily:
                                                      'SFUIText_Regular',
                                                  color: Colors.red,
                                                ),
                                              ),
                                              onPressed: () {
                                                watchmeeBloc
                                                        .fetchDeleteWatchmee =
                                                    BehaviorSubject<
                                                        ApiResponseModel>();
                                                AppRoutes.showLoader(context);
                                                watchmeeBloc.deleteWatchMee(
                                                    allWatchmee[index]['id']);
                                                watchmeeBloc.getDeleteWatchMee
                                                    .listen((data) {
                                                  if (data.status == 200) {
                                                    updateWatchMeeData();
                                                    // setState(() {});
                                                    AppRoutes.dismissLoader(
                                                        context);
                                                    Navigator.pop(
                                                        context, 'Delete');
                                                  } else {
                                                    AppRoutes.dismissLoader(
                                                        context);
                                                    AlertBox().show(
                                                        context,
                                                        'Alert',
                                                        'Your watchmee not deleted',
                                                        "Ok", (data) {
                                                      Navigator.pop(
                                                          context, 'Cancel');
                                                    });
                                                  }
                                                });
                                              },
                                            )
                                          : Container(),
                                    ],
                                    cancelButton: CupertinoActionSheetAction(
                                      child: const Text(
                                        'Cancel',
                                        style: TextStyle(
                                          fontFamily: 'SFUIText_Regular',
                                        ),
                                      ),
                                      isDefaultAction: true,
                                      onPressed: () => Navigator.of(context,
                                              rootNavigator: true)
                                          .pop('Cancel'),
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                      allWatchmee[index]['text'] != ""
                          ? Container(
                              margin:
                                  EdgeInsets.only(left: 20, top: 5, bottom: 10),
                              child: Text(
                                '${allWatchmee[index]['text']}',
                                style: TextStyle(
                                  color: Colors.black,
                                  fontWeight: FontWeight.w500,
                                  fontSize: 14,
                                  fontFamily: 'SFUIText_Semibold',
                                ),
                              ),
                            )
                          : Container(),
                      Center(
                        child: Container(
                          // child: Chewie(
                          //   controller: ChewieController(
                          //     videoPlayerController:
                          //         // VideoPlayerController.network(
                          //         //     "${allWatchmee[index]['file']}"),
                          //         listOfVideos[index],
                          //     aspectRatio: 3 / 2,
                          //     autoPlay: false,
                          //     // looping: true,
                          //   ),
                          // ),
                          // child: listOfVideos[index].value.initialized
                          //     ? Chewie(
                          //         controller: ChewieController(
                          //           videoPlayerController: listOfVideos[index],
                          //           autoInitialize: true,
                          //           looping: false,
                          //           autoPlay: false,
                          //           errorBuilder: (context, errorMessage) {
                          //             return Center(
                          //               child: Text(
                          //                 errorMessage,
                          //                 style: TextStyle(color: Colors.white),
                          //               ),
                          //             );
                          //           },
                          //         ),
                          //       )
                          //     : CircularProgressIndicator(),
                          child: VideoWidget(
                              url: allWatchmee[index]['file'], play: false),
                          // child: ExampleVideo(
                          //   videoUrl: allWatchmee[index]['file'],
                          // ),
                          // child: listOfVideos.length != 0
                          //     ? Chewie(
                          //         key: new PageStorageKey(
                          //             allWatchmee[index]['file']),
                          //         controller: ChewieController(
                          //           videoPlayerController: listOfVideos[index],
                          //           autoInitialize: true,
                          //           looping: false,
                          //           autoPlay: false,
                          //           errorBuilder: (context, errorMessage) {
                          //             return Center(
                          //               child: Text(
                          //                 errorMessage,
                          //                 style: TextStyle(color: Colors.white),
                          //               ),
                          //             );
                          //           },
                          //         ),
                          //       )
                          //     : CircularProgressIndicator(
                          //         valueColor: new AlwaysStoppedAnimation<Color>(
                          //           AppTheme.colors.primaryBlue,
                          //         ),
                          //       ),
                        ),
                      ),
                      Row(
                        children: <Widget>[
                          Spacer(),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                margin: EdgeInsets.only(
                                  top: 5,
                                  right: 20,
                                ),
                                child: new RawMaterialButton(
                                  child: new Image(
                                    image: AssetImage('images/brokenHeart.png'),
                                    color: allWatchmee[index]['isDisLiked'] ==
                                                false ||
                                            allWatchmee[index]['isDisLiked'] ==
                                                null
                                        ? AppTheme.colors.primaryGrey
                                        : AppTheme.colors.primaryRed,
                                    fit: BoxFit.cover,
                                    height: 20,
                                    width: 20,
                                  ),
                                  shape: new CircleBorder(),
                                  elevation: 8,
                                  fillColor: Colors.white,
                                  padding: EdgeInsets.only(top: 2.5),
                                  onPressed: () {
                                    if (allWatchmee[index]['isDisLiked'] ==
                                            null ||
                                        allWatchmee[index]['isDisLiked'] ==
                                            false) {
                                      showMinutesDialog(
                                          context,
                                          allWatchmee[index]['user']['id'],
                                          allWatchmee[index],
                                          'How much time do you want to take?',
                                          false,
                                          1,
                                          updateWatchMeeData());
                                      // Future.delayed(Duration(seconds: 3)).then(
                                      //     (value) => updateWatchMeeData());
                                    }
                                  },
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(
                                  bottom: 5,
                                  right: 20,
                                ),
                                child: Text(
                                  allWatchmee[index]['disLikeCount'] == null
                                      ? '0 Dislike'
                                      : '${allWatchmee[index]['disLikeCount']} Dislike',
                                  style: likeanddislike,
                                ),
                              ),
                            ],
                          ),
                          // Spacer(),
                          Container(
                            child: RichText(
                              text: TextSpan(
                                children: <TextSpan>[
                                  TextSpan(
                                    text: hour.toString().length == 1
                                        ? '0$hour'
                                        : '$hour',
                                    style: hoursCount,
                                  ),
                                  TextSpan(
                                    text: ':',
                                    style: hoursCount,
                                  ),
                                  TextSpan(
                                    text: minute.toString().length == 1
                                        ? '0$minute'
                                        : '$minute',
                                    style: hoursCount,
                                  ),
                                ],
                              ),
                            ),
                          ),
                          // Spacer(),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                margin: EdgeInsets.only(
                                  top: 5,
                                  left: 20,
                                ),
                                child: new RawMaterialButton(
                                  child: new Icon(
                                    Icons.favorite,
                                    color: Colors.white,
                                    size: 22.0,
                                  ),
                                  shape: new CircleBorder(),
                                  elevation: 8,
                                  fillColor: allWatchmee[index]['isLiked'] ==
                                              false ||
                                          allWatchmee[index]['isLiked'] == null
                                      ? AppTheme.colors.primaryGrey
                                      : AppTheme.colors.primaryRed,
                                  padding: EdgeInsets.only(top: 2.5),
                                  onPressed: () {
                                    if (allWatchmee[index]['isLiked'] == null ||
                                        allWatchmee[index]['isLiked'] ==
                                            false) {
                                      showMinutesDialog(
                                          context,
                                          allWatchmee[index]['user']['id'],
                                          allWatchmee[index],
                                          'How much time do you want to donate?',
                                          true,
                                          1,
                                          updateWatchMeeData());
                                      // Future.delayed(Duration(seconds: 3)).then(
                                      //     (value) => updateWatchMeeData());
                                    }
                                  },
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(left: 20, bottom: 5),
                                child: Text(
                                  allWatchmee[index]['likeCount'] == null
                                      ? '0 Like'
                                      : '${allWatchmee[index]['likeCount']} Like',
                                  style: likeanddislike,
                                ),
                              ),
                            ],
                          ),
                          Spacer(),
                        ],
                      ),
                      Container(
                        color: Colors.grey,
                        height: 0.3,
                      )
                    ],
                  ),
                );
              },
            ),
          )
        : RefreshIndicator(
            color: AppTheme.colors.primaryBlue,
            onRefresh: refreshList,
            child: SingleChildScrollView(
              child: Container(
                height: MediaQuery.of(context).size.height / 2.5,
                width: MediaQuery.of(context).size.width,
                margin: EdgeInsets.only(
                    top: MediaQuery.of(context).size.height / 4, bottom: 50),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      width: MediaQuery.of(context).size.height / 3,
                      child: Text(
                          'Post a video or a picture to make itsmee. more colorful!',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontFamily: 'SFUIText_Medium',
                            color: AppTheme.colors.primaryBlue,
                            fontSize: 20,
                          )),
                    ),
                    Container(
                      // color: Colors.red,
                      child: Image.asset(
                        'images/downArrow.png',
                        color: AppTheme.colors.primaryBlue,
                        height: MediaQuery.of(context).size.height / 6,
                        width: MediaQuery.of(context).size.width / 6,
                        fit: BoxFit.cover,
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
  }

  showMinutesDialog(
      BuildContext context,
      int userId,
      dynamic data,
      String message,
      bool value,
      int blocChoice,
      ValueChanged onButtonPressed) {
    return showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) => AddingMinutee(
              dataThreeId: data,
              userId: userId,
              message: message,
              value: value,
              blocChoice: blocChoice,
              onButtonPressed: onButtonPressed,
            ));
    // return AddingMinutee();
  }

  void containerForSheet<T>({BuildContext context, Widget child}) {
    showCupertinoModalPopup<T>(
      context: context,
      builder: (BuildContext context) => child,
    ).then<void>((T value) {
      if (value != null) {
        Scaffold.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '$value',
              style: TextStyle(
                fontFamily: 'SFUIText_Regular',
              ),
            ),
            duration: Duration(milliseconds: 800),
            backgroundColor: value == 'Delete' ? Colors.red : Colors.black,
          ),
        );
      }
    });
  }
}

and this is my video widget

import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:itsmee/theme/theme.dart';
import 'package:video_player/video_player.dart';

class VideoWidget extends StatefulWidget {
  final bool play;
  final String url;

  const VideoWidget({Key key, @required this.url, @required this.play})
      : super(key: key);

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

class _VideoWidgetState extends State<VideoWidget> {
  Future<void> _initializeVideoPlayerFuture;
  VideoPlayerController videoWidgetController;

  @override
  void initState() {
    super.initState();
    videoWidgetController = new VideoPlayerController.network(widget.url);
    _initializeVideoPlayerFuture = videoWidgetController.initialize().then((_) {
      setState(() {});
    });
  }

  @override
  void dispose() {
    videoWidgetController.dispose();
    videoWidgetController?.pause()?.then((_) {
      videoWidgetController?.dispose();
    });
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initializeVideoPlayerFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return Container(
            // color: Colors.red,
            // key: new PageStorageKey(widget.url),
            // elevation: 0.0,
            child: Chewie(
              key: new PageStorageKey(widget.url),
              controller: ChewieController(
                videoPlayerController: videoWidgetController,
                // aspectRatio: 3 / 2,
                aspectRatio: videoWidgetController.value.aspectRatio,
                // Prepare the video to be played and display the first frame
                autoInitialize: true,
                looping: false,
                autoPlay: false,
                // Errors can occur for example when trying to play a video
                // from a non-existent URL
                errorBuilder: (context, errorMessage) {
                  return Center(
                    child: Text(
                      errorMessage,
                      style: TextStyle(color: Colors.white),
                    ),
                  );
                },
              ),
            ),
          );
        } else {
          return Center(
            child: CircularProgressIndicator(
              valueColor: new AlwaysStoppedAnimation<Color>(
                  AppTheme.colors.primaryBlue),
            ),
          );
        }
      },
    );
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants