import 'dart:async'; import 'dart:io'; import 'package:chewie/chewie.dart'; import 'package:flustars/flustars.dart' as FlutterStars; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:image_picker/image_picker.dart'; import 'package:liftmanager/common/common.dart'; import 'package:liftmanager/net/api_service.dart'; import 'package:liftmanager/res/iconfont.dart'; import 'package:liftmanager/res/resources.dart'; import 'package:liftmanager/utils/fast_notification.dart'; import 'package:liftmanager/utils/oss_upload.dart'; import 'package:liftmanager/utils/theme_utils.dart'; import 'package:liftmanager/utils/toast.dart'; import 'package:liftmanager/utils/utils.dart'; import 'package:liftmanager/widgets/app_bar.dart'; import 'package:liftmanager/widgets/selected_video_change.dart'; import 'package:orientation/orientation.dart'; import 'package:video_player/video_player.dart'; import '../../brand_page.dart'; class VideoUpload extends StatefulWidget { @override State createState() { return VideoUploadState(); } } class VideoUploadState extends State { String selectedBrandName = ''; String brandName = "品牌"; int brandIdss; bool showBrandSelectionPanel = false; VideoPlayerController _controller; VideoPlayerController _controllerFile; ChewieController _chewieController; String videoUrl; String str; String imagesUrl; double percent = 0.0; @override void initState() { super.initState(); } List brandList; Future getBrandList() async { await NewApiService().getBrandListType(null, onSuccess: (res) { if (res != null) { brandList = res; setState(() {}); } }, onError: (code, msg) { toasts(msg); }); } ///选择视频 void selectPicker() { showDialog( context: context, builder: (BuildContext context) { return SimpleDialog( title: Text("选择方式"), children: ["拍照", '从手机相册选择'].map((String value) { print("$value"); return SimpleDialogOption( child: Text( "${value}", style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500), ), onPressed: () { _getImage(value == '拍照' ? 1 : 0); Navigator.of(context).pop(); }, ); }).toList()); }); } void _getImage(int key) async { try { await ImagePicker.pickVideo( source: key == 1 ? ImageSource.camera : ImageSource.gallery, ).then((File f) async { if (f != null) { _controllerFile = VideoPlayerController.file(f); _controllerFile.initialize().then((val) { _controllerFile.setLooping(true); int seconds = _controllerFile.value.duration.inSeconds; print("视频时长:$seconds"); int fileSize = f.lengthSync(); //单位B print("视频大小:${fileSize}"); print("视频大小:${f.path}"); if (seconds <= 300) { _uploadImage(f.path); } else { toasts("视频时长不能大于5分钟!"); } }).catchError((error) { print(error); print("error"); toasts("上传失败,不支持此格式"); }); } }); } catch (e) { toasts("没有权限,无法打开相册!"); } } void _uploadImage(filePath) async { showPercent(context, () { dismissLoading(context); toasts("上传失败"); }, () { if (videoUrl == null && str != null) { setState(() { videoUrl = str; settingVideVc(); print("videoUrl:" + videoUrl); dismissLoading(context); toasts("上传成功"); }); } }); String uploadName = OssUtil.instance.getImageUploadName(filePath); await NewApiService.uploadImage(context, uploadName, filePath).then((data) { if (data.statusCode == 200) { str = NewApiUrl.URL_UPLOAD_IMAGE_OSS + "/" + uploadName; print("str:" + str); print(videoUrl); if (str != null) { Map obj = {"uploadName": uploadName, "success": true}; FastNotification.push("percent", obj); } } else { Map obj = {"uploadName": uploadName, "success": false}; FastNotification.push("percent", obj); } }).catchError((data) { Map obj = {"uploadName": uploadName, "success": false}; FastNotification.push("percent", obj); }); } settingVideVc() { _controller?.pause(); _controller?.dispose(); _chewieController?.dispose(); _controller = VideoPlayerController.network(Utils.getImagePath(videoUrl)); _chewieController = ChewieController( videoPlayerController: _controller, aspectRatio: 3 / 2, allowFullScreen: false, isLive: true, autoPlay: false, looping: true, // startAt: Duration(seconds: 1,minutes: 1), showControls: true, deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp], // 是否在 UI 构建的时候就加载视频 autoInitialize: true, // 拖动条样式颜色 materialProgressColors: new ChewieProgressColors( playedColor: Colors.red, handleColor: Colors.blue, backgroundColor: Colors.grey, bufferedColor: Colors.lightGreen, ), ); } @override void dispose() { _controller?.pause(); _controller?.dispose(); _chewieController.dispose(); FlutterStars.SpUtil.putString('uploadName', ""); // player.release(); super.dispose(); } // 焦点控制 FocusNode focusNode1 = new FocusNode(); GlobalKey _formKey = new GlobalKey(); TextEditingController _titleController = new TextEditingController(); TextEditingController _descController = new TextEditingController(); @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; double height = MediaQuery.of(context).size.height; if (width > height) { // SystemChrome.setPreferredOrientations([ // DeviceOrientation.portraitUp, // ]); OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp); } return Scaffold( resizeToAvoidBottomPadding: false, //不让键盘弹上去 appBar: MyAppBar( centerTitle: "上传视频", ), body: GestureDetector( onTap: () { // 点击空白页面关闭键盘 FocusScope.of(context).requestFocus(focusNode1); }, child: Stack( children: [ Container( child: ListView(children: [ Form( key: _formKey, //设置globalKey,用于后面获取FormState // autovalidate: true, //开启自动校验 child: Column( children: [ ChioseThisRight( label: "电梯品牌", value: selectedBrandName, fun: () { setState(() { showBrandSelectionPanel = true; }); getBrandList(); }), SizedBox(height: 10), Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ // Container(height:13 ,width: 100,color:Color(0xff5589FF) ,), Container( padding: EdgeInsets.only( left: 10, ), decoration: BoxDecoration( border: Border( left: BorderSide( width: 2, color: Colors.blue, ), ), ), child: Text( "视频标题", style: TextStyle( fontSize: 14, color: Color(0xff333333), ), textAlign: TextAlign.left, ), ), ], ), Container( height: 80, padding: EdgeInsets.only( left: 12, right: 12, bottom: 20), child: TextFormField( // autofocus: true, maxLength: 50, cursorColor: Color(0xffcccccc), controller: _titleController, maxLines: 5, decoration: InputDecoration( contentPadding: EdgeInsets.all(0), hintText: '请输入你上传视频的标题', hintStyle: TextStyle(color: Color(0xffcccccc)), focusedBorder: InputBorder.none, border: InputBorder.none, // filled: true, // 背景色 // fillColor: Colors.cyan.withAlpha(35), // icon: Icon(Icons.person) ), // 校验 validator: (val) { return val.trim().length > 0 ? null : "不能为空"; }), ), Divider(), SizedBox(height: 10), Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Container( padding: EdgeInsets.only( left: 10, ), decoration: BoxDecoration( border: Border( left: BorderSide( width: 2, color: Colors.blue, ), ), ), child: Text( "视频简介", style: TextStyle( fontSize: 14, color: Color(0xff333333), ), textAlign: TextAlign.left, ), ), ], ), Container( height: 120, padding: EdgeInsets.only( left: 12, right: 12, bottom: 20), child: TextFormField( // autofocus: true, maxLength: 500, cursorColor: Color(0xffcccccc), controller: _descController, maxLines: 5, decoration: InputDecoration( contentPadding: EdgeInsets.all(0), hintText: '请输入您上传视频的简介', hintStyle: TextStyle(color: Color(0xffcccccc)), focusedBorder: InputBorder.none, border: InputBorder.none, ), // 校验 validator: (val) { return val.trim().length > 0 ? null : "不能为空"; }), ), Divider(), SizedBox( height: 20, ), Container( color: ThemeUtils.getTabsBg(context), padding: EdgeInsets.symmetric(horizontal: 10), child: Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ Stack( children: [ Container( height: 150, width: 150, child: SelectedVideo( image: videoUrl, videoPlay: videoPlay(), onTap: () { if (videoUrl == null) { selectPicker(); } }, ), ), (videoUrl != null) ? Positioned( top: 0, right: 0, child: GestureDetector( onTap: () { // print(index); // imagesUrl = null; setState(() { videoUrl = null; str = null; _controller.pause(); // player.reset(); }); }, child: Icon( const IconData(0xe651, fontFamily: "Iconfont"), size: 24.0, color: Color(0xff999999), ), )) : Container() ], ), Container( padding: EdgeInsets.only(left: 10), child: Text( "(建议时长<3分钟,大小<50M)", style: TextStyle( fontSize: ScreenUtil().setSp(13), color: Color(0xffCCCCCC)), textAlign: TextAlign.left, ), ), ], )), SizedBox( height: ScreenUtil().setWidth(80), ), ], ), ) ])), Positioned( bottom: 0, left: 0, child: Container( width: width, padding: EdgeInsets.only( top: ScreenUtil().setWidth(15), bottom: ScreenUtil().setWidth(10), left: ScreenUtil().setWidth(10), right: ScreenUtil().setWidth(10), ), color: ThemeUtils.getDialogTextFieldColor(context), child: Container( height: 45, decoration: BoxDecoration( borderRadius: BorderRadius.circular(ScreenUtil().setWidth(22)), color: Color(0xff5589FF), ), child: FlatButton( // padding: EdgeInsets.all(15.0), child: Text("确认上传"), textColor: Colors.white, onPressed: () { if (brandIdss == null) { toasts("请选择品牌"); return; } if (videoUrl == null || videoUrl == "") { toasts("请上传视频"); return; } if ((_formKey.currentState as FormState).validate()) { dynamic obj = { "brandId": brandIdss, "title": _titleController.text, "descr": _descController.text, "url": videoUrl, // "cover": images, "checkFlag": 2, "statuz": 1, "platformFlag": 1, "userId": FlutterStars.SpUtil.getString(Constant.userId), }; showLoading(context, "正在提交..."); NewApiService().addVideo(obj, onSuccess: (res) { dismissLoading(context); toasts("提交成功"); if (_controller != null) { _controller.pause(); } Navigator.pop(context); }, onError: (code, msg) { dismissLoading(context); toasts(msg); }); } }, ), ), )), if (showBrandSelectionPanel) Positioned( top: 0, left: 0, child: GestureDetector( onTap: () { setState(() { showBrandSelectionPanel = false; }); }, child: Container( width: width, height: height, color: Color.fromRGBO(0, 0, 0, 0.5), ), ), ), if (showBrandSelectionPanel) Positioned( top: 0, right: 0, child: Container( width: width * 0.8, height: height, color: Colors.white, child: brandList == null ? loadCircle() : BrandSelectionPanel( brandList: brandList, onTapBrand: (records) { setState(() { selectedBrandName = records.name; brandIdss = records.id; showBrandSelectionPanel = false; }); }, ), ), ), ], ), ), ); } Widget loadCircle() { return Container( padding: EdgeInsets.only(top: 10, bottom: 10), color: ThemeUtils.getTabsBg(context), child: Center( child: SpinKitFadingCircle( color: Colors.blueAccent, size: 30.0, ), ), ); } Widget videoPlay() { if (_controller == null) return Container(); return Container( child: ClipRRect( borderRadius: BorderRadius.circular(5), child: new Chewie(controller: _chewieController), )); } } class ChioseThisRight extends StatelessWidget { ChioseThisRight( {Key key, this.value, this.label, this.fun, this.labelText = '请选择'}) : super(key: key); String value; String label; Function fun; String labelText; @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; return InkWell( onTap: () { fun(); }, child: Container( padding: EdgeInsets.only( top: ScreenUtil().setWidth(15), bottom: ScreenUtil().setWidth(15)), margin: EdgeInsets.only(left: ScreenUtil().setWidth(15)), decoration: BoxDecoration( border: Border( bottom: BorderSide(width: 0.5, color: Colours.line), ), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( label, style: TextStyle( fontSize: 14, color: Color(0xff333333), ), textAlign: TextAlign.start, ), value.isEmpty ? Container( child: Row(children: [ Text( labelText, style: TextStyle(color: Color(0xff666666), fontSize: 13), textAlign: TextAlign.start, ), Icon( Iconfont.gengduo, size: 13.0, // color: Color(0xffcccccc), ), // Container( // padding: EdgeInsets.only(top: 3), // ), SizedBox(width: 10) ]), ) : Container( padding: EdgeInsets.only(right: ScreenUtil().setWidth(15)), child: Row(children: [ Text( value, style: TextStyle( color: Color(0xff222222), fontSize: 13, ), textAlign: TextAlign.start, ), ]), ), ]), ), ); } }