My problem is that the video works fine on web view but doesn't show or work in the Android emulator. I want to play this video in an emulator also. And all the videos are asset videos. If anyone knows the solution or if anyone can help please help. Thank You
**Below is the code which I wrote for the video **
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:cached_video_player/cached_video_player.dart';
class VideoApp extends StatefulWidget {
const VideoApp({Key? key}) : super(key: key);
#override
State<VideoApp> createState() => _VideoAppState();
}
class _VideoAppState extends State<VideoApp> {
late VideoPlayerController _controller;
late Future<void> _initializeVideoPlayerFuture;
#override
void initState() {
super.initState();
// Create and store the VideoPlayerController. The VideoPlayerController
// offers several different constructors to play videos from assets, files,
// or the internet.
_controller = VideoPlayerController.network(
'assets/videos/animation 1 final.mp4',
);
_initializeVideoPlayerFuture = _controller.initialize();
}
#override
void dispose() {
// Ensure disposing of the VideoPlayerController to free up resources.
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: VideoPlayer(_controller),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
if (_controller.value.isPlaying) {
_controller.pause();
} else {
// If the video is paused, play it.
_controller.play();
}
});
},
// Display the correct icon depending on the state of the player.
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
)
);
}
}
[https://i.stack.imgur.com/8X0OX.png][1]
Your are calling from network but giving an asset path.
_controller = VideoPlayerController.network(
'assets/videos/animation 1 final.mp4',
);
Related
We're building an Obstacle Detection System for visually impared person using mobile camera for college project.
I've made a simple camera app. How to find the focal length of android camera in this app? My
teacher assigned me this task but since i'm not well familiar in flutter. However i made a simple camera app through the help of internet.
I want someone to help me out find the focal length of the android camera. The source code of my camera app is:
// import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
Future<void> main() async {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<CameraDescription>? cameras;
CameraController? controller;
// XFile? image; //for caputred image
#override
void initState() {
loadCamera();
super.initState();
}
loadCamera() async {
cameras = await availableCameras();
if (cameras != null) {
controller = CameraController(cameras![0], ResolutionPreset.max);
//cameras[0] = first camera, change to 1 to another camera
controller!.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
} else {
print("No any camera found");
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("DRISTI"),
backgroundColor: Color(0xFF2899bd),
),
body: Container(
child: Column(children: [
Container(
child: controller == null
? Center(child: Text("Loading Camera..."))
: !controller!.value.isInitialized
? Center(
child: CircularProgressIndicator(),
)
: CameraPreview(controller!)),
])),
);
}
}
Use the CameraDescription class provided by the camera package
Upgrading to Flutter 2.8.1 causes flickering when navigating between screens in apps that contain ads. In particular, the flickering happens when navigating to a new screen from another screen that has a banner ad. When commenting out the banner the flickering goes away.
The problem is not producible using Flutter 2.5.3.
The issue was originally raised in googleads-mobile-flutter but after investigating the issue further it is now believed to be a problem with the Flutter SDK.
To produce the problem, run the attached application code using google_mobile_ads: 1.0.1 and Flutter 2.8.0.
Video sample, code sample and flutter doctor -v output produced by #maheshmnj
Code sample:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(home: HomeScreen());
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(child: ListView.builder(itemBuilder: (context, index) {
return ListTile(
title: Text('Item $index'),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return const ProducDetailPage();
}));
},
);
})),
const CustomBannerAd()
],
),
);
}
}
class ProducDetailPage extends StatelessWidget {
const ProducDetailPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Produc Detail'),
),
body: Column(children: const [
SizedBox(
height: 150,
child: Placeholder(
color: Colors.red,
),
),
SizedBox(
height: 150,
child: Placeholder(
color: Colors.green,
),
),
CustomBannerAd()
]));
}
}
class CustomBannerAd extends StatefulWidget {
const CustomBannerAd({Key? key}) : super(key: key);
#override
_CustomBannerAdState createState() => _CustomBannerAdState();
}
class _CustomBannerAdState extends State<CustomBannerAd> {
BannerAd? _anchoredAdaptiveAd;
var _isLoaded = false;
late Orientation _currentOrientation;
#override
void didChangeDependencies() {
super.didChangeDependencies();
_currentOrientation = MediaQuery.of(context).orientation;
_loadAd();
}
#override
void dispose() {
super.dispose();
_anchoredAdaptiveAd?.dispose();
}
Future<void> _loadAd() async {
await _anchoredAdaptiveAd?.dispose();
if (mounted) {
setState(() {
_anchoredAdaptiveAd = null;
_isLoaded = false;
});
}
final AnchoredAdaptiveBannerAdSize? size =
await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
MediaQuery.of(context).size.width.truncate());
if (size == null) {
debugPrint('Unable to get height of anchored banner.');
return;
}
_anchoredAdaptiveAd = BannerAd(
adUnitId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/6300978111'
: 'ca-app-pub-3940256099942544/2934735716',
size: size,
request: const AdRequest(
nonPersonalizedAds: false,
),
listener: BannerAdListener(
onAdLoaded: (Ad ad) {
debugPrint("Ad loaded");
if (mounted) {
setState(() {
_anchoredAdaptiveAd = ad as BannerAd;
_isLoaded = true;
});
}
},
onAdFailedToLoad: (Ad ad, LoadAdError error) {
debugPrint('$BannerAd failedToLoad: $error');
ad.dispose();
},
onAdOpened: (Ad ad) => debugPrint('$BannerAd onAdOpened.'),
onAdClosed: (Ad ad) => debugPrint('$BannerAd onAdClosed.'),
),
);
return _anchoredAdaptiveAd?.load();
}
#override
Widget build(BuildContext context) {
return OrientationBuilder(builder: (context, orientation) {
if (_currentOrientation == orientation &&
_anchoredAdaptiveAd != null &&
_isLoaded) {
return Container(
color: Colors.transparent,
width: _anchoredAdaptiveAd!.size.width.toDouble(),
height: _anchoredAdaptiveAd?.size.height.toDouble(),
child: AdWidget(ad: _anchoredAdaptiveAd!),
);
}
// Reload the ad if the orientation changes.
if (_currentOrientation != orientation) {
_currentOrientation = orientation;
_loadAd();
}
return const SizedBox.shrink();
});
}
}
is there any solution?
Screenshots and videos
change your google_mobile_ads plugin with this :
google_mobile_ads:
git:
url: https://github.com/SuaMusica/googleads-mobile-flutter.git
path: packages/google_mobile_ads
ref: feature/suamusica
if there is a yellow underscore in git text, just add the following code to pubspec.yaml
publish_to: 'none'
I also faced the same issue. And it's only when you used fluter sdk 2.8 to 2.10. It's also raised on flutter github repo. (https://github.com/flutter/flutter/issues/95343).
The solution is to upgrade flutter sdk to 3.0.2 and update google_mobile_ads 1.3.0.
My app has 2 bottom tabs first one is to capture an Image and second one is to scan QR code through camera.
for Camera i'm using camera: ^0.9.4+1 plugin and for QR code its scan: ^1.4.3 https://pub.dev/packages/scan
once app is restarted you can tap on QR code tab its working then tab on Camera its working too now again tapping on QR tab it shows some wired errors it seems camera not properly disposed or any thing.
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:snapi/controllers/home/home.controller.dart';
class CaptureTab extends StatefulWidget {
final List<CameraDescription> cameras;
const CaptureTab({Key? key, required this.cameras}) : super(key: key);
#override
_CaptureTabState createState() => _CaptureTabState();
}
class _CaptureTabState extends State<CaptureTab> {
Size size = Get.size;
final HomeController controller = Get.find();
#override
void initState() {
super.initState();
initializeCamera(0);
}
late CameraController _controller; //To control the camera
late Future<void> _initializeControllerFuture;
List<File> capturedImages = [];
initializeCamera(int cameraIndex) async {
_controller = CameraController(
widget.cameras[cameraIndex],
ResolutionPreset.medium,
);
_initializeControllerFuture = _controller.initialize();
}
#override
void dispose() {
super.dispose();
_controller.dispose();
}
#override
Widget build(BuildContext context) {
Size size = Get.size;
return Scaffold(
backgroundColor: Colors.white,
body: Stack(
children: [
SizedBox(
height: size.height - size.height * 0.076,
child: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return CameraPreview(_controller);
} else {
return const Center(child: CircularProgressIndicator());
}
},
),
),
],
),
);
}
}
QR code scanning code.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:scan/scan.dart';
import 'package:snapi/controllers/home/home.controller.dart';
class ResourceTab extends StatefulWidget {
const ResourceTab({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() => _ResourceTabState();
}
class _ResourceTabState extends State<ResourceTab> {
String _platformVersion = 'Unknown';
final HomeController homeController = Get.find();
ScanController controller = ScanController();
String qrcode = 'Unknown';
#override
void initState() {
super.initState();
initPlatformState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Expanded(
flex: 4,
child: ScanView(
controller: controller,
scanAreaScale: .7,
scanLineColor: Colors.green.shade400,
onCapture: (data) async {
// do something interesting
},
),
),
],
),
);
}
Future<void> initPlatformState() async {
String platformVersion;
try {
platformVersion = await Scan.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
}
The best explanation of error is look like this.
this is the error i got while opning QR scaning view after Camera preview.
E/CameraCaptureSession( 7546): Session 0: Exception while stopping repeating:
android.hardware.camera2.CameraAccessException: CAMERA_ERROR (3): cancelRequest:459: Camera 0: Error clearing streaming request: Function not implemented (-38)
To play video within the alert dialog I am using the below code. But Video is not playing. Is it possible to play video within the Alert Dialog? Does anyone has a solution to this please share it with me.
Future<void> _initializeVideoPlayerFuture;
VideoPlayerController _controller;
_controller = VideoPlayerController.network(
video_base_url+videoUrl,
);
// Initialize the controller and store the Future for later use.
_initializeVideoPlayerFuture = _controller.initialize();
// Use the controller to loop the video.
_controller.setLooping(true);
// If the video is playing, pause it.
if (_controller.value.isPlaying) {
_controller.pause();
} else {
// If the video is paused, play it.
_controller.play();
}
ContainerResponsive(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width-50,
height: 150,
child: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the VideoPlayerController has finished initialization, use
// the data it provides to limit the aspect ratio of the video.
return AspectRatio(
aspectRatio: _controller.value.aspectRatio,
// Use the VideoPlayer widget to display the video.
child: VideoPlayer(_controller),
);
} else {
// If the VideoPlayerController is still initializing, show a
// loading spinner.
return const Center(
child: CircularProgressIndicator(),
);
}
},
)
),
Make a new Stateful widget class like this for video player , initialized video player controller and video player widget here
import 'package:approved/src/constants/colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:video_player/video_player.dart';
class VideoWidget extends StatefulWidget {
final String? url;
final bool? play;
const VideoWidget({#required this.url, #required this.play});
#override
_VideoWidgetState createState() => _VideoWidgetState();
}
class _VideoWidgetState extends State<VideoWidget> {
late VideoPlayerController _controller;
Future<void>? _initializeVideoPlayerFuture;
#override
void initState() {
super.initState();
_controller = VideoPlayerController.network(widget.url!);
_initializeVideoPlayerFuture = _controller.initialize().then((_) {
// Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
setState(() {});
});
if (widget.play!) {
_controller.play();
_controller.setLooping(true);
}
}
#override
void didUpdateWidget(VideoWidget oldWidget) {
if (oldWidget.play != widget.play) {
if (widget.play!) {
_controller.play();
_controller.setLooping(true);
} else {
_controller.pause();
}
}
super.didUpdateWidget(oldWidget);
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Stack(children: [
Container(
color: Colors.white,
child: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return VideoPlayer(_controller);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
),
]);
}
}
Now you can use this widget anywhere you have to just pass the video url and playing parameter true/false.
Like I am using in showDialog method
playVideo(
BuildContext context,
) {
return showDialog(
context: context,
builder: (context) {
return Center(
child: SizedBox(
height: 300,
width: 300,
child: VideoWidget(url: url, play: true)));
});
}
I want to create a RIVE animation with flutter. I followed a tutorial in YouTube. I wrote the same thing but when I execute two errors is displayed
(RiveFile.import (data);
file.mainArtboard;)
Here is the code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rive/rive.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyPage(),
);
}
}
class MyPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Using Rive'),
),
body: RocketContainer());
}
}
class RocketContainer extends StatefulWidget {
#override
_RocketContainerState createState() => _RocketContainerState();
}
class _RocketContainerState extends State<RocketContainer> {
Artboard _artboard;
RiveAnimationController _rocketController;
#override
void initState() {
_loadRiveFile();
super.initState();
}
void _loadRiveFile() async {
final bytes = await rootBundle.load('assets/rocket.riv');
final file = RiveFile.import(bytes);
setState(() {
_artboard = file.mainArtboard;
});
}
void _launch() async {
_artboard.addController(
_rocketController = SimpleAnimation('launch'),
);
setState(() => _rocketController.isActive = true);
}
void _fall() async {
_artboard.addController(
_rocketController = SimpleAnimation('fall'),
);
setState(() => _rocketController.isActive = true);
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height - 250,
child: _artboard != null
? Rive(
artboard: _artboard,
fit: BoxFit.cover,
)
: Container()),
TextButton(onPressed: () => _launch(), child: Text('launch')),
TextButton(onPressed: () => _fall(), child: Text('fall'))
],
);
}
}
errors:
The current Dart SDK version is 2.10.5.
Because animation depends on cupertino_icons >=1.0.1 which requires SDK version >=2.12.0-0 <3.0.0, version solving failed.
pub get failed (1; Because animation depends on cupertino_icons >=1.0.1 which requires SDK version >=2.12.0-0 <3.0.0, version solving failed.)
*error: Instance member 'import' can't be accessed using static access. (static_access_to_instance_member at [animation] lib\main.dart:47)
*error: The getter 'mainArtboard' isn't defined for the type 'bool'. (undefined_getter at [animation] lib\main.dart:50)
You could have a look at the example provided with the updated and latest documentation of Rive in their official Github repository.
Control playing and pausing a looping animation:
import 'package:flutter/material.dart';
import 'package:rive/rive.dart';
class PlayPauseAnimation extends StatefulWidget {
const PlayPauseAnimation({Key? key}) : super(key: key);
#override
_PlayPauseAnimationState createState() => _PlayPauseAnimationState();
}
class _PlayPauseAnimationState extends State<PlayPauseAnimation> {
// Controller for playback
late RiveAnimationController _controller;
// Toggles between play and pause animation states
void _togglePlay() =>
setState(() => _controller.isActive = !_controller.isActive);
/// Tracks if the animation is playing by whether controller is running
bool get isPlaying => _controller.isActive;
#override
void initState() {
super.initState();
_controller = SimpleAnimation('idle');
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RiveAnimation.network(
'https://cdn.rive.app/animations/vehicles.riv',
controllers: [_controller],
// Update the play state when the widget's initialized
onInit: () => setState(() {}),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _togglePlay,
tooltip: isPlaying ? 'Pause' : 'Play',
child: Icon(
isPlaying ? Icons.pause : Icons.play_arrow,
),
),
);
}
}
To play an animation from an asset bundle, use:
RiveAnimation.asset('assets/vehicles.riv'
in place of
RiveAnimation.network('https://cdn.rive.app/animations/vehicles.riv',
This line:
_controller = SimpleAnimation('idle');
attempts to play an animation called 'idle'. If your animation is named differently, try replacing the name here.