Flutter QR Scan is not working after Camera Tab - android

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)

Related

Find focal length in flutter

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

In android emulator video doesn't show (Flutter)

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',
);

fix net::err_unknown_url_scheme whatsapp link on flutter webview

Please I want to know how to launch WhatsApp in the Flutter webview app or launch WhatsApp from the browser in Flutter, have used many codes with no errors but they do not work.Am using mac m1
and vscode
import 'package:coinpaga/Connectivity_Provider.dart';
import 'package:coinpaga/services/local_notification_service.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'homepage.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:colorful_safe_area/colorful_safe_area.dart';
/// Receive message when app is in background solution for on
message
Future<void> backgroundHandler(RemoteMessage message)async{
print(message.data.toString());
print(message.notification!.title);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
LocalNotificationServices.initialize();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => ConnectivityProvider(),
child: HomePage(),
)
],
child:MaterialApp(
title: 'coinpaga',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: ColorfulSafeArea(
color: HexColor("#2e2a42"),
top: true,
bottom: false,
left: false,
right: false,
child: HomePage(),
)
),
);
}
}
Home.dart
import 'package:coinpaga/Connectivity_Provider.dart';
import 'package:coinpaga/no_internet.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:provider/provider.dart';
class HomePage extends StatefulWidget {
// ignore: unused_field
final _flutterwebview = FlutterWebviewPlugin();
HomePage({ Key? key }) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
void initState() {
super.initState();
Provider.of<ConnectivityProvider>(context, listen:
false).startMonitoring();
}
#override
Widget build(BuildContext context) {
return pageUI();
}
#override
void dispose() {
_flutterwebview.dispose();
super.dispose();
}
}
Widget pageUI() {
return Consumer<ConnectivityProvider>(
builder: (context, model, child) {
return model.isOnline
? WebviewScaffold(
url: 'https://coinpaga.com',
withLocalStorage: true,
withJavascript: true,
scrollBar: false,
initialChild: Center(child: Text('Loading...')),
) : NoInternet();
},
);
}
// ignore: camel_case_types
class _flutterwebview {
static void dispose() {}
}
Please help me go through it.
String text = "Hello World !! Hey There";
String url = "https://wa.me/?text=${Uri.encodeFull(text)}";
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url),
mode: LaunchMode.externalApplication);
}
First, add url_launcher, then I use this code to launch whatsapp on flutter webview and works.
WebView(
initialUrl: getUrl(_url),
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (NavigationRequest request) async {
if (request.url
.startsWith('https://api.whatsapp.com/send?phone')) {
print('blocking navigation to $request}');
List<String> urlSplitted = request.url.split("&text=");
String phone = "0123456789";
String message =
urlSplitted.last.toString().replaceAll("%20", " ");
await _launchURL(
"https://wa.me/$phone/?text=${Uri.parse(message)}");
return NavigationDecision.prevent;
}
print('allowing navigation to $request');
return NavigationDecision.navigate;
},
)
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
You can use url_launcher to launch URLs.
You can give https://api.whatsapp.com/send/?phone=(phone_number) URL to launch.
For the launching the WhatsApp Website use launch('https://api.whatsapp.com/send/?phone=(phone_number)')
Make sure you give your country code without (+).

Severe glitch when navigating to a screen with google_mobile_ads

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.

how create a RIVE animation with flutter

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.

Categories

Resources