VideoPlayer becomes black when dismissing a miniplayer in Flutter - flutter

I have a miniplayer where I have a video widget (I use better_player which depends on chewie and video_player). Everything works great unless I want to dismiss the miniplayer. The video is replaced with a black screen. I did some debugging and found out that for some reason the dispose() method is called on my video_widget twice (when I start dismissing and when I end dismissing my miniplayer). Below is a video that shows this behavior:
Could you help me with fixing this issue?
EDIT
I did some more debugging and found out that it is probably related to the video widget or better_player package. Also, I found out that when using chewie behavior is nearly the same but with chewie when I start dismissing video gets black for a millisecond and then initializes again and starts playing from the beginning. Here is the code of my `video widget class.
import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/services.dart';
import 'package:cook_it/screens/longs_page/providers/providers.dart';
import 'package:path_provider/path_provider.dart';
import 'package:better_player/better_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class LongsVideoItem extends StatefulWidget {
const LongsVideoItem({Key? key }) : super(key: key);
#override
_LongsVideoItemState createState() => _LongsVideoItemState();
}
class _LongsVideoItemState extends State<LongsVideoItem> {
void _toggleVideoControls(bool show){
if (show){
_betterPlayerController.setControlsEnabled(true);
}else{
_betterPlayerController.setControlsEnabled(false);
}
}
Future _saveAssetVideoToFile() async {
final content = await rootBundle.load("assets/videos/second.mp4");
final directory = await getApplicationDocumentsDirectory();
final file = File("${directory.path}/second.mp4");
_directory = "${directory.path}/second.mp4";
file.writeAsBytesSync(content.buffer.asUint8List());
}
BetterPlayerController _betterPlayerController = BetterPlayerController(const BetterPlayerConfiguration());
dynamic _directory;
#override
void initState() {
_saveAssetVideoToFile().then((value) {
final BetterPlayerDataSource betterPlayerDataSource = BetterPlayerDataSource(
BetterPlayerDataSourceType.file,
_directory.toString(),
);
_betterPlayerController = BetterPlayerController(
const BetterPlayerConfiguration(
deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
aspectRatio: 16/9,
autoPlay: true,
controlsConfiguration: BetterPlayerControlsConfiguration(showControlsOnInitialize: false),
),
betterPlayerDataSource: betterPlayerDataSource,
);
});
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Consumer(
builder: (context, watch, _){
if (watch(videoShowControlsProvider).state == true){
_toggleVideoControls(true);
}else if (watch(videoShowControlsProvider).state == false){
_toggleVideoControls(false);
}
return BetterPlayer(controller: _betterPlayerController,);
}
);
}
}
here are the logs when I start dismissing
I/ExoPlayerImpl(16667): Release cd87770 [ExoPlayerLib/2.14.1] [HWCLT, CLT-L29, HUAWEI, 28] [goog.exo.core]
W/ACodec (16667): forcing OMX state to Idle when received shutdown in ExecutingState
3
E/BufferQueueProducer(16667): [SurfaceTexture-0-16667-145] cancelBuffer: BufferQueue has been abandoned
I/chatty (16667): uid=10234(com.example.cook_it) JNISurfaceTextu identical 10 lines
E/BufferQueueProducer(16667): [SurfaceTexture-0-16667-145] cancelBuffer: BufferQueue has been abandoned
D/SurfaceUtils(16667): disconnecting from surface 0x797bec7010, reason disconnectFromSurface
I/ExoPlayerImpl(16667): Init 8b84e21 [ExoPlayerLib/2.14.1] [HWCLT, CLT-L29, HUAWEI, 28]
V/AudioManager(16667): getStreamVolume treamType: 3
V/AudioManager(16667): isStreamMute streamType: 3
V/AudioManager(16667): getStreamMaxVolume treamType: 3
E/ (16667): [ZeroHung]zrhung_get_config: Get config failed for wp[0x0008]
I/OMXClient(16667): IOmx service obtained
I/ACodec (16667): In onAllocateComponent create compenent, codec name: OMX.hisi.video.decoder.avc
D/SurfaceUtils(16667): connecting to surface 0x797c027010, reason connectToSurface
I/MediaCodec(16667): [OMX.hisi.video.decoder.avc] setting surface generation to 17067154
D/SurfaceUtils(16667): disconnecting from surface 0x797c027010, reason connectToSurface(reconnect)
D/SurfaceUtils(16667): connecting to surface 0x797c027010, reason connectToSurface(reconnect)
E/ACodec (16667): [OMX.hisi.video.decoder.avc] setPortMode on output to DynamicANWBuffer failed w/ err -2147483648
I/HwExtendedCodec(16667): mime is [video/avc] at setVideoFormat
I/ACodec (16667): codec does not support config priority (err -22)
2
I/ACodec (16667): [OMX.hisi.video.decoder.avc] got color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) err=0(NO_ERROR)
I/ACodec (16667): [OMX.hisi.video.decoder.avc] using color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) and dataspace 0x104
I/ACodec (16667): onStart
D/SurfaceUtils(16667): disconnecting from surface 0x797c027010, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils(16667): connecting to surface 0x797c027010, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils(16667): set up nativeWindow 0x797c027010 for 1920x1080, color 0x30d, rotation 0, usage 0x20002900
6
W/MapperHal(16667): buffer descriptor with invalid usage bits 0x2000
2
I/ACodec (16667): [OMX.hisi.video.decoder.avc] got color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) err=0(NO_ERROR)
I/ACodec (16667): [OMX.hisi.video.decoder.avc] using color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) and dataspace 0x104
2
I/ACodec (16667): [OMX.hisi.video.decoder.avc] got color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) err=0(NO_ERROR)
I/ACodec (16667): [OMX.hisi.video.decoder.avc] using color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) and dataspace 0x104
D/SurfaceUtils(16667): disconnecting from surface 0x797c027010, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils(16667): connecting to surface 0x797c027010, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils(16667): set up nativeWindow 0x797c027010 for 1920x1088, color 0x30d, rotation 0, usage 0x20002900
W/ACodec (16667): [OMX.hisi.video.decoder.avc] setting nBufferCountActual to 19 failed: -2147483648
18
W/MapperHal(16667): buffer descriptor with invalid usage bits 0x2000
I/ACodec (16667): date space update : 0x104
I believe that for some reason this widget calls the dispose() method when I start dismissing. But why is that happening and how can I prevent that from happening?

I found the answer. The problem was in the miniplayer package. In case someone has the same problem comment here and I will explain how to fix it.

Related

Can't fetch NetworkImage for Flutter from Google Cloud Storage bucket

I want to load a NetworkImage in Flutter but can't get it to work because of a:
Handshake error in client (OS Error:
CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate(handshake.cc:393))
Does not work (Image from Google Cloud Storage + Cloud CDN)
NetworkImage("https://cdn.vaandra.com/items/f69f662f-41ff-4bb1-bd50-75a70b7ca6a5/439806b1-cacc-4d58-85a5-601bcb825fe3-p-500")
However this does work (test image from the webz)
NetworkImage("https://picsum.photos/250?image=9")
This is the full error message:
======== Exception caught by image resource service ================================================
The following HandshakeException was thrown resolving an image codec:
Handshake error in client (OS Error:
CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate(handshake.cc:393))
When the exception was thrown, this was the stack:
#0 _SecureFilterImpl._handshake (dart:io-patch/secure_socket_patch.dart:99:46)
#1 _SecureFilterImpl.handshake (dart:io-patch/secure_socket_patch.dart:142:25)
#2 _RawSecureSocket._secureHandshake (dart:io/secure_socket.dart:911:54)
#3 _RawSecureSocket._tryFilter (dart:io/secure_socket.dart:1040:19)
<asynchronous suspension>
Image provider: NetworkImage("https://cdn.vaandra.com/items/f69f662f-41ff-4bb1-bd50-75a70b7ca6a5/439806b1-cacc-4d58-85a5-601bcb825fe3-p-500", scale: 1.0)
Image key: NetworkImage("https://cdn.vaandra.com/items/f69f662f-41ff-4bb1-bd50-75a70b7ca6a5/439806b1-cacc-4d58-85a5-601bcb825fe3-p-500", scale: 1.0)
====================================================================================================
Although the error claims that this is a certificate problem I can't understand how it does work with that public image that also comes through https?
Create a class that extends the http override
class MyHttpOverrides extends HttpOverrides{
#override
HttpClient createHttpClient(SecurityContext context){
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
}
}
And use it in the main function
void main(){
HttpOverrides.global = new MyHttpOverrides();
runApp(MyApp());
}

Flutter stripe_checkout Payment Method Exception

I'm using Flutter stripe_checkout: ^1.0.0 and saw some odd behaviour.
When the checkout button is clicked just once, the screen would turn blank with the following printout. On Stripe dashboard, it says, "Incomplete - The customer has not entered their payment method'.
I/flutter (32631): Checkout session id cs_test_a10k5Lsopaz9JupfebE9pW77ZgUpucfzCrh1WTKX9KcApdbKztnZiz1SKe
I/WebViewFactory(32631): Loading com.google.android.webview version 83.0.4103.106 (code 410410681)
I/cr_VariationsUtils(32631): Requesting new seed from IVariationsSeedServer
I/cr_LibraryLoader(32631): Loaded native library version number "83.0.4103.106"
I/cr_CachingUmaRecorder(32631): Flushed 3 samples from 3 histograms.
I/TetheringManager(32631): registerTetheringEventCallback:com.healthcare.jaaba
W/GooglePlayServicesUtil(32631): Google Play Store is missing.
W/GooglePlayServicesUtil(32631): Google Play Store is missing.
W/GooglePlayServicesUtil(32631): Google Play Store is missing.
W/GooglePlayServicesUtil(32631): Google Play Store is missing.
E/cr_PlatformSer-Internal(32631): UsageReporting query failed
W/ealthcare.jaab(32631): Accessing hidden method Landroid/media/AudioManager;->getOutputLatency(I)I (greylist, reflection, allowed)
D/HostConnection(32631): HostConnection::get() New Host Connection established 0xf4e7e280, tid 752
E/cr_PlatformSer-Internal(32631): Unable to determine Safe Browsing user opt-in preference
D/HostConnection(32631): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0
D/EGL_emulation(32631): eglCreateContext: 0xf4e7c140: maj 3 min 0 rcv 3
D/EGL_emulation(32631): eglMakeCurrent: 0xf4e7c140: ver 3 0 (tinfo 0xaf33b210) (first time)
D/EGL_emulation(32631): eglMakeCurrent: 0xf4e60d10: ver 3 0 (tinfo 0xf51b1d50) (first time)
W/Gralloc4(32631): allocator 3.x is not supported
I/VideoCapabilities(32631): Unsupported profile 4 for video/mp4v-es
W/cr_MediaCodecUtil(32631): HW encoder for video/avc is not available on this device.
D/EGL_emulation(32631): eglCreateContext: 0xf4e7f1d0: maj 3 min 0 rcv 3
I/ealthcare.jaab(32631): NativeAlloc concurrent copying GC freed 50165(3378KB) AllocSpace objects, 15(428KB) LOS objects, 49% free, 3769KB/7539KB, paused 2.245ms total 147.024ms
W/ealthcare.jaab(32631): Reducing the number of considered missed Gc histogram windows from 124 to 100
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
However, when the checkout button is clicked 3 - 5 times continuously, the card form appears and the payment would be successful.
I/flutter (32631): Checkout session id cs_test_a1ZwZrvL4812TEpjFwQ649RMYjirJr9TMwQVZ29JYrjGj54gmqkCtTyfTW
I/flutter (32631): Checkout session id cs_test_a13D23W9EY1SgLBqYIZLAHTvFBcHKY1wUIiZdr3Kb6XPNsrrLEfj3KJjkj
I/ealthcare.jaab(32631): NativeAlloc concurrent copying GC freed 7125(419KB) AllocSpace objects, 0(0B) LOS objects, 49% free, 3431KB/6863KB, paused 1.352ms total 189.441ms
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/flutter (32631): Checkout session id cs_test_a1QsxT2t7H68MpvgLinDukwOBzwW1W21ktnbQdqB25R6t2b0TE5mO4u9jj
I/flutter (32631): Checkout session id cs_test_a1o2VPwBSq0RRW6PlSKnGr554hoWFIOrPy1NZWnLveMqAZyLX6iVYKFr0y
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/flutter (32631): Checkout session id cs_test_a1uWleO9v9VAwUAra957z8uHbpOwNyp24nZYgAQ2aOLHqwt3hBcOtAg8Yf
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/fingerprinted/js/stripe-a07f9e62b0b55658b30abedf1005cae0.js (1)
I/chatty (32631): uid=10139(com.healthcare.jaaba) identical 1 line
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/fingerprinted/js/stripe-a07f9e62b0b55658b30abedf1005cae0.js (1)
I/Choreographer(32631): Skipped 31 frames! The application may be doing too much work on its main thread.
I/chromium(32631): [INFO:CONSOLE(265)] "Uncaught ReferenceError: PaymentRequest is not defined", source: https://pay.google.com/gp/p/js/pay.js (265)
Flutter Application: checkout_screen.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:stripe_checkout/stripe_checkout.dart';
import 'package:flutter/material.dart';
import '../../../../utils/env.dart';
import '../widgets/example_scaffold.dart';
import '../../../../utils/api_endpoints.dart';
import 'platforms/stripe_checkout.dart' if (dart.library.js)
'platforms/stripe_checkout_web.dart';
class CheckoutScreenExample extends StatefulWidget {
const CheckoutScreenExample({Key? key}) : super(key: key);
#override
_CheckoutScreenExample createState() => _CheckoutScreenExample();
}
class _CheckoutScreenExample extends State<CheckoutScreenExample> {
#override
Widget build(BuildContext context) {
return ExampleScaffold(
title: 'Checkout Page',
padding: const EdgeInsets.all(16),
children: [
const SizedBox(height: 120),
Center(
child: ElevatedButton(
onPressed: checkout,
child: const Text('Open Checkout'),
),
)
],
);
}
Future<void> checkout() async {
final String sessionId = await _createCheckoutSession();
final result = await redirectToCheckout(
context: context,
sessionId: sessionId,
publishableKey: stripePublishableKey,
successUrl: 'https://checkout.stripe.dev/success',
canceledUrl: 'https://checkout.stripe.dev/cancel',
);
if (mounted) {
final text = result.when(
success: () => 'Paid successfully',
canceled: () => 'Checkout canceled',
error: (e) => 'Error $e',
redirected: () => 'Redirected successfully',
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(text)),
);
}
}
Future<String> _createCheckoutSession() async {
final stripePayURL = Uri.parse(ApiUrl.stripePayUrl);
final response = await http.get(
stripePayURL,
headers: <String, String>{'Authorization': 'Bearer ' + token,
},
);
final Map<String, dynamic> bodyResponse = json.decode(response.body);
final id = bodyResponse['checkout_session_id'] as String;
debugPrint('Checkout session id $id');
return id;
}
}
Flask Backend: billing.py
#api_blueprint.route('/stripe_pay', methods=['GET'])
#token_auth.login_required
def stripe_pay():
cart_id = basic_auth.current_user().id
transaction = Transaction.query.filter(Transaction.cart_id==cart_id).first()
price = stripe.Price.create(
unit_amount=transaction.count_grand_total(),
currency=transaction.currency,
)
session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[{
'price': price,
'quantity': 1,
}],
mode='payment',
success_url=url_for('api.success', cart_id=cart_id, _external=True) + '?cart_id=cart_id' + '?session_id={CHECKOUT_SESSION_ID}',
cancel_url=url_for('home.index', _external=True),
)
return jsonify ({
'checkout_session_id': session['id'],
'checkout_public_key': checkout_public_key,
'cart_id': int(cart_id)
})
I would appreciate if someone show me how to fix this. Thank you.

Flutter, simple method channel not working

I followed this https://docs.flutter.dev/development/platform-integration/platform-channels
D/InputTransport(12698): Input channel constructed: 'ClientS', fd=180
D/InputMethodManager(12698): prepareNavigationBarInfo() DecorView#9959d90[MainActivity]
D/InputMethodManager(12698): getNavigationBarColor() -16711423
V/InputMethodManager(12698): Starting input: tba=com.abc ic=null mNaviBarColor -16711423 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
D/InputMethodManager(12698): startInputInner - Id : 0
I/SurfaceControl(12698): nativeRelease nativeObject s[-5476376642254367232]
I/SurfaceControl(12698): nativeRelease nativeObject e[-5476376642254367232]
I/SurfaceControl(12698): nativeRelease nativeObject s[-5476376642254367552]
I/SurfaceControl(12698): nativeRelease nativeObject e[-5476376642254367552]
continuously shows this.
The strange thing is that in Android project, clean project, rebuild, and turn off and restart Android studio sometimes works. (Only sometimes I can see the print("it works"); in MainActivity more specifically, inside of "configureFlutterEngine" function

How to mock Socket.io client in Flutter tests

I'm using socket_io_client v0.9.12 in my flutter app (still not using null safety). I am creating a socket connection with my back-end server when the app starts and allow child widgets to access it using a provider.
I am trying to start creating the connection in the constructor so that when I need to use the socket client, it would probably be initialized already.
This is my provider class which has the creation of the socket connection:
class SocketClient {
SocketClient() {
_initializer = initialize();
}
Future _initializer;
/// Socket client
Socket client;
/// Wait until the client is properly connected with the server
Future finishInitializing() => _initializer;
/// Initialize the socket connection with the server
Future initialize() async {
final completer = Completer<Socket>();
final socket = io(
'http://localhost:3000/gateway',
OptionBuilder() //
.setTransports(['websocket'])
.disableAutoConnect()
.setQuery({'token': 'TOKEN'})
.build(),
)..connect();
socket
..onConnect((_) {
completer.complete(socket);
});
client = await completer.future;
}
}
The main app widget I have:
#override
Widget build(BuildContext context) {
return Provider<SocketClient>(
create: (_) => SocketClient(),
builder: (context, _) {
return Scaffold(
...
);
},
);
}
This is how I am trying to use the socket client:
Future<void> foo(SocketClient socketClient) async {
await socketClient.finishInitializing();
final socket = socketClient.client;
socket.on(eventName, (dynamic uploadDrawingEvent) {
...
});
}
Everything works fine up to now. 🎉
However, when I try to run my tests that depend on this socket client, I see the below error:
Pending timers:
Timer (duration: 0:00:20.000000, periodic: false), created:
#0 new FakeTimer._ (package:fake_async/fake_async.dart:284:41)
#1 FakeAsync._createTimer (package:fake_async/fake_async.dart:248:27)
#2 FakeAsync.run.<anonymous closure> (package:fake_async/fake_async.dart:181:19)
#5 Manager.connect (package:socket_io_client/src/manager.dart:232:19)
#6 Manager.open (package:socket_io_client/src/manager.dart:194:41)
#7 Socket.connect (package:socket_io_client/src/socket.dart:104:8)
#8 SocketClient.initialize (package:flutter_app/web/services/socket_provider.dart:48:8)
<asynchronous suspension>
(elided 2 frames from dart:async)
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown running a test:
A Timer is still pending even after the widget tree was disposed.
'package:flutter_test/src/binding.dart':
Failed assertion: line 1241 pos 12: '!timersPending'
When the exception was thrown, this was the stack:
#2 AutomatedTestWidgetsFlutterBinding._verifyInvariants (package:flutter_test/src/binding.dart:1241:12)
#3 TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:803:7)
<asynchronous suspension>
(elided 2 frames from class _AssertionError)
...
initialize function keeps hanging after client = await completer.future; line. That future is not resolved even after the test is finished (see the error).
I would like to get ideas on how I can mock this socket client properly to avoid this error.
I'm looking more towards an answer which mocks the functionality of the socket client because I have some more tests to write to cover the event handlers.
Thank you in advance! 🙏
You can use await IOOverrides for override standard Socket method like socketConnect
Exemple:
await IOOverrides.runZoned(() async {
your code
}, socketConnect: (host, port, {sourceAddress, int sourcePort = 0, timeout}) => Future.value(mockSocket));

Flutter: Camera disconnect exception when other camera apps are opened

I'm currently using the flutter camera package to record and save videos, but I've noticed that the camera preview runs into an exception when the device's camera is opened on another app or when face unlock is used on the lock screen.
I've tried using didChangeAppLifecycleState to possibly fetch or reinitialize the camera, but there's no success yet.
await model.fetchCameras();
if (model.cameras.isNotEmpty) {
await model.onNewCameraSelected(model.cameras[model.cameraIndex], true);
}
}
This issue is currently opened here and here, but haven't been resolved.
I get this exception when the device's camera is opened in another app. I tried disposing the camera and reinitializing it in the sample code above, but it doesn't work.
E/CameraCaptureSession(31468): android.hardware.camera2.CameraAccessException: CAMERA_DISCONNECTED (2): cancelRequest:458: Camera device no longer alive
E/CameraCaptureSession(31468): at android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:814)
E/CameraCaptureSession(31468): at android.hardware.camera2.impl.ICameraDeviceUserWrapper.cancelRequest(ICameraDeviceUserWrapper.java:95)
E/CameraCaptureSession(31468): at android.hardware.camera2.impl.CameraDeviceImpl.stopRepeating(CameraDeviceImpl.java:1134)
E/CameraCaptureSession(31468): at android.hardware.camera2.impl.CameraCaptureSessionImpl.close(CameraCaptureSessionImpl.java:526)
E/CameraCaptureSession(31468): at android.hardware.camera2.impl.CameraCaptureSessionImpl$2.onDisconnected(CameraCaptureSessionImpl.java:737)
E/CameraCaptureSession(31468): at android.hardware.camera2.impl.CameraDeviceImpl$7.run(CameraDeviceImpl.java:242)
E/CameraCaptureSession(31468): at android.os.Handler.handleCallback(Handler.java:873)
E/CameraCaptureSession(31468): at android.os.Handler.dispatchMessage(Handler.java:99)
E/CameraCaptureSession(31468): at android.os.Looper.loop(Looper.java:214)
E/CameraCaptureSession(31468): at android.app.ActivityThread.main(ActivityThread.java:6981)
E/CameraCaptureSession(31468): at java.lang.reflect.Method.invoke(Native Method)
E/CameraCaptureSession(31468): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/CameraCaptureSession(31468): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
E/CameraCaptureSession(31468): Caused by: android.os.ServiceSpecificException: cancelRequest:458: Camera device no longer alive (code 4)
E/CameraCaptureSession(31468): at android.os.Parcel.createException(Parcel.java:1980)
E/CameraCaptureSession(31468): at android.os.Parcel.readException(Parcel.java:1934)
E/CameraCaptureSession(31468): at android.os.Parcel.readException(Parcel.java:1884)
E/CameraCaptureSession(31468): at android.hardware.camera2.ICameraDeviceUser$Stub$Proxy.cancelRequest(ICameraDeviceUser.java:402)
E/CameraCaptureSession(31468): at android.hardware.camera2.impl.ICameraDeviceUserWrapper.cancelRe
Any Ideas, on how to force the camera package to reinitialize?
On resume re initialise Camera
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_controller != null
? _initializeControllerFuture = _controller.initialize()
: null; //on pause camera is disposed, so we need to call again "issue is only for android"
}
}
checkout https://medium.com/#navinkumar0118/take-a-picture-using-flutter-camera-a9c11d282632