Ho to catch flutter video_player plugin error? - flutter

How to catch error on flutter video_player plugin?
the error is Source error. when this error occurred I want to display error message.
I/ExoPlayerImpl(31473): Init 98a4284 [ExoPlayerLib/2.9.6] [kenzo, Redmi Note 3, Xiaomi, 23]
E/ExoPlayerImplInternal(31473): Source error.
E/ExoPlayerImplInternal(31473): com.google.android.exoplayer2.source.UnrecognizedInputFormatException: None of the available extractors (MatroskaExtractor, FragmentedMp4Extractor, Mp4Extractor, Mp3Extractor, AdtsExtractor, Ac3Extractor, TsExtractor, FlvExtractor, OggExtractor, PsExtractor, WavExtractor, AmrExtractor) could read the stream.
E/ExoPlayerImplInternal(31473): at com.google.android.exoplayer2.source.ExtractorMediaPeriod$ExtractorHolder.selectExtractor(ExtractorMediaPeriod.java:973)
E/ExoPlayerImplInternal(31473): at com.google.android.exoplayer2.source.ExtractorMediaPeriod$ExtractingLoadable.load(ExtractorMediaPeriod.java:891)
E/ExoPlayerImplInternal(31473): at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:381)
E/ExoPlayerImplInternal(31473): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
E/ExoPlayerImplInternal(31473): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
E/ExoPlayerImplInternal(31473): at java.lang.Thread.run(Thread.java:818)
I/flutter (31473): Another exception was thrown: A ChewieController was used after being disposed.
I/ExoPlayerImpl(31473): Release 98a4284 [ExoPlayerLib/2.9.6] [kenzo, Redmi Note 3, Xiaomi, 23] [goog.exo.core]
my code
animeVidBloc.vidCtrl = VideoPlayerController.network(streamurl.src)
..initialize().then((_) {
animeVidBloc.vidCtrl.pause();
animeVidBloc.cheCtrl = ChewieController(
videoPlayerController: animeVidBloc.vidCtrl,
aspectRatio: animeVidBloc.vidCtrl.value.aspectRatio,
autoPlay: false,
looping: false,
allowedScreenSleep: false,
);
animeVidBloc.isLoadingData = false;
animeVidBloc.isLoadingVideo = false;
animeVidBloc.cheCtrl.pause();
animeVidBloc.rebuildWidgets(ids: ['body', 'download']);
});
using .catch after initialize().then doesn't catch the error,
example video https://str09.vidoza.net/x4lfoiywwbzpvjumxbaeidisvq6cmoufczvmicnesasm4zqpyunkofpekfla/v.mp4

You can attach listener to the VidePlayerController object to catch states of the controller.
VideoPlayerController _controller = VideoPlayerController.network(
"https://str09.vidoza.net/x4lfoiywwbzpvjumxbaeidisvq6cmoufczvmicnesasm4zqpyunkofpekfla/v.mp4")
..initialize();
_controller.addListener(() {
if (_controller.value.hasError) {
print(_controller.value.errorDescription);
}
if (_controller.value.initialized) {}
if (_controller.value.isBuffering) {}
});

Related

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: Error clearing streaming request: Function not implemented

I am working on an app in flutter that uses the camera.
I have followed the basic flutter tutorial
https://flutter.dev/docs/cookbook/plugins/picture-using-camera
However, when I am on a screen using the CameraPreview widget, and I navigate to another app that uses the camera, like snapchat, I see the following error when opening snapchat (the error comes from my app), has anyone else seen this before?
Returning to my app shows the camera in a frozen/paused state.
I/CameraManagerGlobal(30470): Camera 0 facing CAMERA_FACING_BACK state now CAMERA_STATE_IDLE for client com.my.cliet API Level 2
I/CameraManagerGlobal(30470): Camera 0 facing CAMERA_FACING_BACK state now CAMERA_STATE_CLOSED for client com.my.cliet API Level 2
E/CameraCaptureSession(30470): Session 0: Exception while stopping repeating:
E/CameraCaptureSession(30470): android.hardware.camera2.CameraAccessException: CAMERA_ERROR (3): cancelRequest:547: Camera 0: Error clearing streaming request: Function not implemented (-38)
E/CameraCaptureSession(30470): at android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:1340)
E/CameraCaptureSession(30470): at android.hardware.camera2.impl.ICameraDeviceUserWrapper.cancelRequest(ICameraDeviceUserWrapper.java:99)
E/CameraCaptureSession(30470): at android.hardware.camera2.impl.CameraDeviceImpl.stopRepeating(CameraDeviceImpl.java:1259)
E/CameraCaptureSession(30470): at android.hardware.camera2.impl.CameraCaptureSessionImpl.close(CameraCaptureSessionImpl.java:578)
E/CameraCaptureSession(30470): at android.hardware.camera2.impl.CameraCaptureSessionImpl$2.onDisconnected(CameraCaptureSessionImpl.java:789)
E/CameraCaptureSession(30470): at android.hardware.camera2.impl.CameraDeviceImpl$7.run(CameraDeviceImpl.java:245)
E/CameraCaptureSession(30470): at android.os.Handler.handleCallback(Handler.java:938)
E/CameraCaptureSession(30470): at android.os.Handler.dispatchMessage(Handler.java:99)
E/CameraCaptureSession(30470): at android.os.Looper.loop(Looper.java:246)
E/CameraCaptureSession(30470): at android.app.ActivityThread.main(ActivityThread.java:8506)
E/CameraCaptureSession(30470): at java.lang.reflect.Method.invoke(Native Method)
E/CameraCaptureSession(30470): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
E/CameraCaptureSession(30470): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
E/CameraCaptureSession(30470): Caused by: android.os.ServiceSpecificException: cancelRequest:547: Camera 0: Error clearing streaming request: Function not implemented (-38) (code 10)
E/CameraCaptureSession(30470): at android.os.Parcel.createExceptionOrNull(Parcel.java:2399)
E/CameraCaptureSession(30470): at android.os.Parcel.createException(Parcel.java:2369)
E/CameraCaptureSession(30470): at android.os.Parcel.readException(Parcel.java:2352)
E/CameraCaptureSession(30470): at android.os.Parcel.readException(Parcel.java:2294)
E/CameraCaptureSession(30470): at android.hardware.camera2.ICameraDeviceUser$Stub$Proxy.cancelRequest(ICameraDeviceUser.java:750)
E/CameraCaptureSession(30470): at android.hardware.camera2.impl.ICameraDeviceUserWrapper.cancelRequest(ICameraDeviceUserWrapper.java:97)
E/CameraCaptureSession(30470): ... 11 more
So I have resolved the issue by adding the following which aren't included in the link that I posted.
in the initState() method I had to manually add the observer
WidgetsBinding.instance!.addObserver(this);
I had to define/modify the didChangeAppLifecycleState(...) function as follows
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
final CameraController? cameraController = _controller;
// App state changed before we got the chance to initialize.
if (cameraController == null || !cameraController.value.isInitialized) {
return;
}
if (state == AppLifecycleState.inactive) {
cameraController.dispose();
} else if (state == AppLifecycleState.resumed) {
this._controller = CameraController(
widget.camera,
ResolutionPreset.medium,
);
if (mounted) {
setState(() {
this._initializeControllerFuture = this._controller.initialize();
});
}
}
}

Flutter audioplayers stop playing after multiple play events

i'm using this code to play sound whenever I click on a widget.
Future<void> playMySound(String who) async{
AudioPlayer advancedPlayer = new AudioPlayer();
audioCache = new AudioCache(fixedPlayer: advancedPlayer);
audioCache.clearCache();
String localFilePath;
audioCache.play('roomSounds/$who', mode: PlayerMode.LOW_LATENCY);
}
Problem:
Whenever I tap for example 15 times on a widget that would play the sound, it would stop playing and throw the following stack:
E/MediaPlayer( 5793): Error (-38,0)
I/flutter ( 5793): hello 0.0
E/MediaPlayerNative( 5793): error (1, -19)
E/MediaPlayer( 5793): Error (1,-19)
E/MediaPlayerNative( 5793): pause called in state 0, mPlayer(0x77ceaa80)
E/MediaPlayerNative( 5793): error (-38, 0)
E/MediaPlayerNative( 5793): Attempt to perform seekTo in wrong state: mPlayer=0x77ceaa80, mCurrentState=0
E/MediaPlayerNative( 5793): error (-38, 0)
E/MediaPlayer( 5793): Error (-38,0)
E/MediaPlayer( 5793): Error (-38,0)
I've tried to use audioCache.clearCache() but with no effect. Only after reloading the application it is possible to play any sound at all.

Uncaught Exception with try catch in Dart

I'm building a flutter app that uses SignalR. For this purpose I'm using signalr_core library. So far things work well when the server is up and running and I provide a valid authentication token, but when I provided a wrong token and start the connection I get the following error:
Error: Expected a value of type 'Error', but got one of type 'WebSocketChannelException'
at Object.throw_ [as throw] (http://localhost:64659/dart_sdk.js:4348:11)
at Object.castError (http://localhost:64659/dart_sdk.js:4319:15)
at Object.cast [as as] (http://localhost:64659/dart_sdk.js:4635:17)
at dart.LegacyType.new.as (http://localhost:64659/dart_sdk.js:6212:60)
at http://localhost:64659/packages/signalr_core/src/json_hub_protocol.dart.lib.js:2129:44
at _RootZone.runUnaryGuarded (http://localhost:64659/dart_sdk.js:37736:11)
at sendError (http://localhost:64659/dart_sdk.js:31344:26)
at _ControllerSubscription.new.[_sendError] (http://localhost:64659/dart_sdk.js:31359:11)
at _ControllerSubscription.new.[_addError] (http://localhost:64659/dart_sdk.js:31282:27)
at _SyncStreamController.new.[_sendError] (http://localhost:64659/dart_sdk.js:34230:39)
at _SyncStreamController.new.[_addError] (http://localhost:64659/dart_sdk.js:34042:27)
at _SyncStreamController.new.addError (http://localhost:64659/dart_sdk.js:34012:24)
at _RootZone.runBinaryGuarded (http://localhost:64659/dart_sdk.js:37753:11)
at sendError (http://localhost:64659/dart_sdk.js:31342:26)
at _ControllerSubscription.new.[_sendError] (http://localhost:64659/dart_sdk.js:31359:11)
at _ControllerSubscription.new.[_addError] (http://localhost:64659/dart_sdk.js:31282:27)
at _SyncStreamController.new.[_sendError] (http://localhost:64659/dart_sdk.js:34230:39)
at _SyncStreamController.new.[_addError] (http://localhost:64659/dart_sdk.js:34042:27)
at _SyncStreamController.new.addError (http://localhost:64659/dart_sdk.js:34012:24)
at _StreamSinkWrapper.new.addError (http://localhost:64659/dart_sdk.js:34339:24)
at _GuaranteeSink.new.[_addError] (http://localhost:64659/packages/stream_channel/src/stream_channel_controller.dart.lib.js:1223:26)
at _GuaranteeSink.new.addError (http://localhost:64659/packages/stream_channel/src/stream_channel_controller.dart.lib.js:1218:24)
at http://localhost:64659/packages/web_socket_channel/html.dart.lib.js:199:36
at _RootZone.runUnary (http://localhost:64659/dart_sdk.js:37810:58)
at _FutureListener.then.handleValue (http://localhost:64659/dart_sdk.js:32771:29)
at handleValueCallback (http://localhost:64659/dart_sdk.js:33319:49)
at Function._propagateToListeners (http://localhost:64659/dart_sdk.js:33357:17)
at _Future.new.[_complete] (http://localhost:64659/dart_sdk.js:33190:25)
at Object._cancelAndValue (http://localhost:64659/dart_sdk.js:38220:24)
at http://localhost:64659/dart_sdk.js:18845:17
at Object._checkAndCall (http://localhost:64659/dart_sdk.js:4558:16)
at Object.dcall (http://localhost:64659/dart_sdk.js:4563:17)
at WebSocket.<anonymous> (http://localhost:64659/dart_sdk.js:104962:23)
Although I did catch the exception in my code.
Here is the connection initialization code:
_connection = HubConnectionBuilder()
.withAutomaticReconnect() //
.withUrl(
_URL,
HttpConnectionOptions(
logging: (level, message) => print(message),
skipNegotiation: true,
transport: HttpTransportType.webSockets,
accessTokenFactory: () {
return Future.value('wrongToken');
},
)) //
.build(); //
As for connection start code:
void start() async {
try {
_streamingStateController.add(StreamingInfo(StreamingState.Starting));
await _connection.start();
_listenToGPSChange();
_streamingStateController.add(StreamingInfo(StreamingState.Started));
} on Exception catch (exception) {
_handleError('Oops. Unable to connect to the server.');
} on Error catch (error) {
_handleError('Oops. Unable to connect to the server.');
}
}
Please not that I get the same error when the connection succeeds (in case of valid parameters) but afterwards a shut down my server and send a message.
So the question is, how do I catch this type of errors?

Bad state: No ProviderScope found in flutter consumer component

When I add flutter consumer component in flutter like this:
SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
sliver: Consumer(
(context, read) {
return read(storiesTypeProvider(articleRequest)).when(
loading: () {
// return SliverFillRemaining(
// child: Center(child: CircularProgressIndicator()));
return SliverToBoxAdapter(child: Center(child: LoadingItem()));
},
error: (err, stack) {
print(err);
return SliverToBoxAdapter(
child: Center(child: Text('Error: $err')));
},
data: (ids) {
//return StoryList(ids: ids,storiesType: articleRequest.storiesType,);
},
);
},
),
)
shows this error:
flutter: [debug] Capture from onError 'package:flutter/src/widgets/nested_scroll_view.dart': Failed assertion: line 806 pos 14: 'position.hasContentDimensions && position.hasPixels': is not true.
flutter: [debug] Capture from onError 'package:flutter/src/widgets/nested_scroll_view.dart': Failed assertion: line 806 pos 14: 'position.hasContentDimensions && position.hasPixels': is not true.
======== Exception caught by widgets library =======================================================
The following StateError was thrown building RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#0ac5b](state: RawGestureDetectorState#734b4(gestures: <none>, behavior: opaque)):
Bad state: No ProviderScope found
The relevant error-causing widget was:
SmartRefresher file:///Users/dolphin/Documents/GitHub/cruise-open/lib/src/page/home/components/homelistdefault_component/view.dart:47:22
When the exception was thrown, this was the stack:
#0 ProviderStateOwnerScope.of (package:flutter_riverpod/src/framework.dart:216:7)
#1 _ConsumerState.didChangeDependencies (package:flutter_riverpod/src/consumer.dart:107:46)
#2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4839:11)
#3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4655:5)
... Normal element mounting (4 frames)
...
====================================================================================================
======== Exception caught by scheduler library =====================================================
'package:flutter/src/widgets/nested_scroll_view.dart': Failed assertion: line 806 pos 14: 'position.hasContentDimensions && position.hasPixels': is not true.
====================================================================================================
======== Exception caught by scheduler library =====================================================
'package:flutter/src/widgets/nested_scroll_view.dart': Failed assertion: line 806 pos 14: 'position.hasContentDimensions && position.hasPixels': is not true.
====================================================================================================
now I am using fish-redux to manage my flutter state, should I must using ProviderScope? what should I do to fix this problem? this is the storiesTypeProvider:
final storiesTypeProvider = FutureProvider.family((ref, type) async {
return await Repo.getArticles(type);
});
If you use flutter_riverpod.
You need to add ProviderScope to the main() function.
Like this:
void main() {
runApp(ProviderScope(child: MyApp()));
}