Error: Bad state: Cannot add new events after calling close - flutter

I am using '''youtube_player_iframe: ^2.1.0''' package for displaying YouTube video in Flutter web app. The video is playing absolutely fine but it gives this error whenever i tap on full screen to play video in full screen also it do not make the video to come on full screen and return to its previous size
ERROR
Error: Bad state: Cannot add new events after calling close
at Object.throw_ [as throw] (http://localhost:42339/dart_sdk.js:5041:11)
at _AsyncBroadcastStreamController.new.add (http://localhost:42339/dart_sdk.js:31586:44)
at controller.YoutubePlayerController.new.add (http://localhost:42339/packages/youtube_player_iframe/src/helpers/youtube_value_builder.dart.lib.js:894:32)
at http://localhost:42339/packages/youtube_player_iframe/src/helpers/youtube_value_builder.dart.lib.js:469:29
at Object._checkAndCall (http://localhost:42339/dart_sdk.js:5246:16)
at Object.dcall (http://localhost:42339/dart_sdk.js:5251:17)
at http://localhost:42339/dart_sdk.js:100646:100
Error: Bad state: Cannot add new events after calling close
at Object.throw_ [as throw] (http://localhost:42339/dart_sdk.js:5041:11)
at _AsyncBroadcastStreamController.new.add (http://localhost:42339/dart_sdk.js:31586:44)
at controller.YoutubePlayerController.new.add (http://localhost:42339/packages/youtube_player_iframe/src/helpers/youtube_value_builder.dart.lib.js:894:32)
at http://localhost:42339/packages/youtube_player_iframe/src/helpers/youtube_value_builder.dart.lib.js:469:29
at Object._checkAndCall (http://localhost:42339/dart_sdk.js:5246:16)
at Object.dcall (http://localhost:42339/dart_sdk.js:5251:17)
at http://localhost:42339/dart_sdk.js:100646:100
CODE :
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:youtube_player_iframe/youtube_player_iframe.dart';
class YoutubePlayerWeb extends StatefulWidget {
final String url;
const YoutubePlayerWeb({Key? key, required this.url}) : super(key: key);
#override
_YoutubePlayerState createState() => _YoutubePlayerState();
}
class _YoutubePlayerState extends State<YoutubePlayerWeb> {
late YoutubePlayerController _controller;
void runYoutubePlay()
{
_controller = YoutubePlayerController(
initialVideoId: YoutubePlayerController.convertUrlToId(widget.url).toString(),
params: const YoutubePlayerParams(
showControls: true,
desktopMode: true,
showFullscreenButton: true,
privacyEnhanced: true,
showVideoAnnotations: true ,
autoPlay: false,
enableCaption: true,
color: 'red',
)
);
}
void youtubePlayerFullScreen()
{
_controller.onEnterFullscreen = ()
{
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
print("ENTERED FULLSCREEN");
};
_controller.onExitFullscreen = ()
{
print("EXITED FULLSCREEN");
};
}
#override
void initState() {
runYoutubePlay();
youtubePlayerFullScreen();
super.initState();
}
#override
void dispose() {
_controller.close();
super.dispose();
}
#override
Widget build(BuildContext context) {
const player = YoutubePlayerIFrame();
return YoutubePlayerControllerProvider(controller: _controller, child: player);
}
}
Please Help me and please tell where am i going wrong ?

The cause of the issue is that an event is being tried to be used on YoutubePlayerController after it has been closed on dispose(). A checker can be used to see if _controller is still open.
if (!_controller.isClosed){
// Add events
}

Related

Flutter: Video player not initialized

I have a video preview widget that takes either a string url or a video file. If the parameter is a String, it downloads the file from online/the cache. With this is mind, my implementation is as follows:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:hero/helpers/cache_manager/cache_manager.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
class WaveVideoPreview extends StatefulWidget {
final File? videoFile;
final String? videoUrl;
WaveVideoPreview({this.videoFile, this.videoUrl});
#override
_WaveVideoPreviewState createState() => _WaveVideoPreviewState();
}
class _WaveVideoPreviewState extends State<WaveVideoPreview> {
late VideoPlayerController? _controller;
late ChewieController _chewieController;
void initState() {
super.initState();
_initAsync();
}
void _initAsync() async {
File? _videoFile = widget.videoFile;
if (_videoFile == null) {
_videoFile = await getVideo(_videoFile);
}
_controller = VideoPlayerController.file(_videoFile!)
..initialize().then((_) {
setState(() {
_chewieController = ChewieController(
videoPlayerController: _controller!,
aspectRatio: _controller!.value.aspectRatio,
autoPlay: false,
looping: true,
allowFullScreen: false,
);
});
});
}
Future<File?> getVideo(File? _videoFile) async {
_videoFile = await MyCache.getVideo(widget.videoUrl!);
return _videoFile;
}
#override
Widget build(BuildContext context) {
return Container(
height: 200.0,
child: (_controller?.value.isInitialized ?? false)
? Chewie(
controller: _chewieController,
)
: SizedBox.shrink(),
);
}
#override
void dispose() {
_controller!.dispose();
_chewieController.dispose();
super.dispose();
}
}
with
static Future<File?> getVideo(String url) async {
DefaultCacheManager _cacheManager = DefaultCacheManager();
File? file = await _cacheManager.getSingleFile(url);
return file;
}
Which is throwing the error:
════════ Exception caught by widgets library ═══════════════════════════════════
The following LateError was thrown building WaveVideoPreview(dirty, state: _WaveVideoPreviewState#659ef):
LateInitializationError: Field '_controller#1875314998' has not been initialized.
The relevant error-causing widget was
WaveVideoPreview
lib/…/widget/wave_tile.dart:84
When the exception was thrown, this was the stack
#0 _WaveVideoPreviewState._controller (package:hero/screens/home/home_screens/views/waves/widget/video/wave_video_preview.dart)
package:hero/…/video/wave_video_preview.dart:1
#1 _WaveVideoPreviewState.build
package:hero/…/video/wave_video_preview.dart:57
Anyone know whats going on? I've tried changing the video player between nullable and non nullable, but still to no avail. Also as you can see i have a null check, but still nothing.
_initAsync is using async and it will take some frame to initialize the controllers.
It would be better to use FutureBuilder for this. or make those nullable and the do a null check while using it.
VideoPlayerController? _controller;
ChewieController? _chewieController;

Camera Live view (Hikvision) with Flutter

I'm building a Flutter app and I need to connect and view live feed of our Hikvision IP camera inside our building:
I have tried these two libraries but they are very old and I couldn't get them to work:
a) flutter_hk: ^1.0.2 => it does not support 'Null Safety' so I was not able to build my application
https://pub.dev/packages/flutter_hk/install
b) remote_ip_camera: ^2.0.0 => it is giving many errors since it is using old widgets like FlatButton & RaisedButton
https://pub.dev/packages/remote_ip_camera/example
How this connection can be done from inside my Flutter app and show the camera feed inside a ‘Container’ widget? I have my camera IP address, port, username and password.
I have looked everywhere but couldn’t find any official documentation from Hikvision or any other IP cameras manufacturer.
I used https://pub.dev/packages/flutter_vlc_player to stream rtsp stream of hikvision camera.
create a widget video_streaming_window.dart with the below code
import 'package:flutter/material.dart';
import 'package:flutter_vlc_player/flutter_vlc_player.dart';
class VideoStreamingWindow extends StatefulWidget {
final String url;
const VideoStreamingWindow({Key key, this.url}) : super(key: key);
#override
State<VideoStreamingWindow> createState() => _VideoStreamingWindowState();
}
class _VideoStreamingWindowState extends State<VideoStreamingWindow> {
VlcPlayerController _videoPlayerController;
#override
void initState() {
super.initState();
_videoPlayerController = VlcPlayerController.network(
widget.url,
autoInitialize: true,
hwAcc: HwAcc.full,
autoPlay: true,
options: VlcPlayerOptions(),
);
}
#override
void dispose() {
super.dispose();
_videoPlayerController.pause();
_videoPlayerController.dispose();
}
#override
Widget build(BuildContext context) {
return VlcPlayer(
controller: _videoPlayerController,
aspectRatio: 16 / 9,
placeholder: const Center(
child: CircularProgressIndicator(
color: Colors.white,
)),
);
}
}
Call it in your UI wherever necessary by VideoStreamingWindow(url: 'rtsp://<username>:<password>#<camera-ip>/ISAPI/Streaming/channels/<channel-no>')

How to get the balance of an account with flutter_web3 package in flutter?

I am using this package and want to get the balance of a random wallet, but I get the following error in Chrome dev console. Where I am missing?
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_web3/ethereum.dart';
import 'package:flutter_web3/ethers.dart';
Future<void> main() async {
runApp(MaterialApp(home: MyApp()));
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool acc = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () async {
if (ethereum != null) {
try {
setState(() {
acc = ethereum!.isConnected();
});
var balance = await provider!.getBalance(
'0xb978C0757977F1717d4888AfFfFaE1023cDbe63B');
print(balance);
} on EthereumUserRejected {
print('User rejected!');
}
}
},
child: Text(acc ? 'Connected' : 'Connect'),
),
],
),
),
);
}
}
Error I get in Browser console:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'providers')
at Web3Provider.new (provider.dart:388:7)
at get provider [as provider] (ethers.dart:34:28)
at main._MyAppState.new.<anonymous> (main.dart:36:41)
at Generator.next (<anonymous>)
at runBody (async_patch.dart:84:54)
at Object._async [as async] (async_patch.dart:123:5)
at main.dart:27:26
at [_handleTap] (ink_well.dart:1005:21)
at tap.TapGestureRecognizer.new.invokeCallback (recognizer.dart:198:24)
at tap.TapGestureRecognizer.new.handleTapUp (tap.dart:613:48)
at [_checkUp] (tap.dart:298:5)
at tap.TapGestureRecognizer.new.handlePrimaryPointer (tap.dart:232:7)
at tap.TapGestureRecognizer.new.handleEvent (recognizer.dart:563:9)
at [_dispatch] (pointer_router.dart:94:12)
at pointer_router.dart:139:9
at LinkedMap.new.forEach (linked_hash_map.dart:21:13)
at [_dispatchEventToRoutes] (pointer_router.dart:137:17)
at pointer_router.PointerRouter.new.route (pointer_router.dart:123:7)
at binding$5.WidgetsFlutterBinding.new.handleEvent (binding.dart:445:19)
at binding$5.WidgetsFlutterBinding.new.dispatchEvent (binding.dart:425:14)
at binding$5.WidgetsFlutterBinding.new.dispatchEvent (binding.dart:329:11)
at [_handlePointerEventImmediately] (binding.dart:380:7)
at binding$5.WidgetsFlutterBinding.new.handlePointerEvent (binding.dart:344:5)
at [_flushPointerEventQueue] (binding.dart:302:7)
at [_handlePointerDataPacket] (binding.dart:285:32)
at Object.invoke1 (platform_dispatcher.dart:1105:13)
at _engine.EnginePlatformDispatcher.__.invokeOnPointerDataPacket (platform_dispatcher.dart:185:5)
at [_onPointerData] (pointer_binding.dart:130:39)
at pointer_binding.dart:543:18
at pointer_binding.dart:496:21
at loggedHandler (pointer_binding.dart:210:16)

Unsupported operation: _Namespace ERROR while using rootbundle.loadString()

I am trying to use mapsforge plugin to use my own compiled map. I am not an experienced flutter developer and don't know so much about loading assets therefore can't figure out what the problem is.
File structure;
pubspec.yaml;
flutter:
uses-material-design: true
assets:
- assets/login/
- assets/maps/render_themes/
- assets/maps/icons
Code;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mapsforge_flutter/core.dart';
import 'package:mapsforge_flutter/maps.dart';
class MapShow extends StatefulWidget {
#override
_MapShowState createState() => _MapShowState();
}
class _MapShowState extends State<MapShow> {
late MapFile mapFile;
late SymbolCache symbolCache;
GraphicFactory graphicFactory = const FlutterGraphicFactory();
DisplayModel displayModel = DisplayModel();
late RenderThemeBuilder renderThemeBuilder;
late String content;
late RenderTheme renderTheme;
late MapDataStoreRenderer jobRenderer;
late MapModel mapModel;
late ViewModel viewModel;
void assignSymbolCache() async {}
#override
void initState() {
super.initState();
rootBundle
.loadString("assets/maps/render_themes/defaultrender.xml")
.then((String s) {
content = s;
});
MapFile.from("assets/maps/akuzem.map", null, null).then((MapFile mf) {
mapFile = mf;
});
symbolCache = FileSymbolCache(rootBundle);
renderThemeBuilder =
RenderThemeBuilder(graphicFactory, symbolCache, displayModel);
renderThemeBuilder.parseXml(content);
renderTheme = renderThemeBuilder.build();
jobRenderer =
MapDataStoreRenderer(mapFile, renderTheme, graphicFactory, true);
mapModel = MapModel(
displayModel: displayModel,
renderer: jobRenderer,
);
viewModel = ViewModel(displayModel: displayModel);
}
#override
Widget build(BuildContext context) {
setState(() {});
return FlutterMapView(
mapModel: mapModel,
viewModel: viewModel,
graphicFactory: graphicFactory);
}
}
Also i saw WidgetsFlutterBinding.ensureInitialized(); in an answer and added my void main() but didnt solved.
Error Showing;
Error in debug console;
Restarted application in 161ms.
Error: Unsupported operation: _Namespace
at Object.throw_ [as throw] (http://localhost:60585/dart_sdk.js:5067:11)
at Function.get _namespacePointer [as _namespacePointer] (http://localhost:60585/dart_sdk.js:56707:17)
at Function._namespacePointer (http://localhost:60585/dart_sdk.js:54523:28)
at Function._dispatchWithNamespace (http://localhost:60585/dart_sdk.js:54526:31)
at io._File.new.exists (http://localhost:60585/dart_sdk.js:54530:23)
at readbufferfile.ReadbufferFile.new._openRaf (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:82:30)
at _openRaf.next (<anonymous>)
at runBody (http://localhost:60585/dart_sdk.js:40590:34)
at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at readbufferfile.ReadbufferFile.new.[_openRaf] (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:77:20)
at readbufferfile.ReadbufferFile.new.length (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:93:29)
at length.next (<anonymous>)
at runBody (http://localhost:60585/dart_sdk.js:40590:34)
at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at readbufferfile.ReadbufferFile.new.length (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:91:20)
at mapfile.MapFile.__._init (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15605:75)
at _init.next (<anonymous>)
at runBody (http://localhost:60585/dart_sdk.js:40590:34)
at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at mapfile.MapFile.__.[_init] (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15602:20)
at from (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15586:34)
at from.next (<anonymous>)
at runBody (http://localhost:60585/dart_sdk.js:40590:34)
at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at Function.from (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15584:20)
at map_show._MapShowState.new.initState (http://localhost:60585/packages/mapping_tool/pages/map/map_show.dart.lib.js:166:23)
in your initState method, you used then, It breaks your order of code.
Try this code :
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mapsforge_flutter/core.dart';
import 'package:mapsforge_flutter/maps.dart';
class MapShow extends StatefulWidget {
#override
_MapShowState createState() => _MapShowState();
}
class _MapShowState extends State<MapShow> {
late MapFile mapFile;
late SymbolCache symbolCache;
GraphicFactory graphicFactory = const FlutterGraphicFactory();
DisplayModel displayModel = DisplayModel();
late RenderThemeBuilder renderThemeBuilder;
late String content;
late RenderTheme renderTheme;
late MapDataStoreRenderer jobRenderer;
late MapModel mapModel;
late ViewModel viewModel;
void assignSymbolCache() async {}
#override
void initState() {
super.initState();
start();
}
start()async{
///use await let u place fields in right order
content = await rootBundle
.loadString("assets/maps/render_themes/defaultrender.xml");
mapFile = await MapFile.from("assets/maps/akuzem.map", null, null);
symbolCache = FileSymbolCache(rootBundle);
renderThemeBuilder =
RenderThemeBuilder(graphicFactory, symbolCache, displayModel);
renderThemeBuilder.parseXml(content);
renderTheme = renderThemeBuilder.build();
jobRenderer =
MapDataStoreRenderer(mapFile, renderTheme, graphicFactory, true);
mapModel = MapModel(
displayModel: displayModel,
renderer: jobRenderer,
);
viewModel = ViewModel(displayModel: displayModel);
///never use set state before widget return, Do it in when your view is ready to load
setState(() {});
}
#override
Widget build(BuildContext context) {
return FlutterMapView(
mapModel: mapModel,
viewModel: viewModel,
graphicFactory: graphicFactory);
}
}

setState() or markNeedsBuild() called during build Exception using Chewie Controller

I have a video playing on the screen using the code below. When I hit the fullscreen icon on the controllers, I get the exception setState() or markNeedsBuild() called during build. The screen should go to fullscreen in the landscape when I hit the icon. It goes but then comes to portrait again (i.e. device orientation).
The following assertion was thrown while dispatching notifications for VideoPlayerController:
setState() or markNeedsBuild() called during build.
Debug console says:
This MaterialControls widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: MaterialControls
dependencies: [_InheritedTheme, _LocalizationsScope-[GlobalKey#8836f], _ChewieControllerProvider]
state: _MaterialControlsState#84529
The widget which was currently being built when the offending call was made was: VideoApp
dirty
state: VideoAppState#8eaa6
When the exception was thrown, this was the stack
Element.markNeedsBuild.<anonymous closure>
Element.markNeedsBuild
State.setState
_MaterialControlsState._updateState
ChangeNotifier.notifyListeners
...
The VideoPlayerController sending notification was: VideoPlayerController#cc7a6(VideoPlayerValue(duration: 0:11:43.069000, size: Size(640.0, 360.0), position: 0:00:03.609000, buffered: [DurationRange(start: 0:00:00.000000, end: 0:00:10.543000)], isPlaying: true, isLooping: false, isBuffering: falsevolume: 1.0, errorDescription: null))
Here is the code which I am using currently.
import 'package:flutter/material.dart';
import 'package:chewie/chewie.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
typedef void EndOfVideo();
class VideoApp extends StatefulWidget {
final VideoAppState _videoAppState = VideoAppState();
final String videoUrl;
final EndOfVideo endOfVideo;
final bool autoPlay;
VideoApp({
this.videoUrl,
this.endOfVideo,
this.autoPlay
});
#override
State<StatefulWidget> createState() => _videoAppState;
}
class VideoAppState extends State<VideoApp> {
bool _eovReached = false;
// bool wasLandscape = false;
// bool leaveFullscreen = false;
VideoPlayerController _videoPlayerController;
ChewieController _chewieController;
VoidCallback listener;
VideoAppState() {
listener = () {
if(_videoPlayerController.value.initialized) {
Duration duration = _videoPlayerController.value.duration;
Duration position = _videoPlayerController.value.position;
if (duration.inSeconds - position.inSeconds < 3) {
if(!_eovReached) {
_eovReached = true;
widget.endOfVideo();
}
}
}
};
}
initialize(){
if(_videoPlayerController != null && _videoPlayerController.value.isPlaying) {
_videoPlayerController.pause();
}
_videoPlayerController = VideoPlayerController.network(
widget.videoUrl
);
if(_chewieController != null) {
_chewieController.dispose();
}
_chewieController = ChewieController(
allowedScreenSleep: false,
allowFullScreen: true,
// uncomment line below to make video fullscreen when play button is hit
// fullScreenByDefault : true,
deviceOrientationsAfterFullScreen: [
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
],
videoPlayerController: _videoPlayerController,
aspectRatio: 16 / 9,
autoPlay: false,
looping: false,
autoInitialize: false,
);
_videoPlayerController.addListener(listener);
_videoPlayerController.initialize();
}
#override
void initState() {
super.initState();
try {
this.initialize();
}catch(e){}
}
#override
void didUpdateWidget(VideoApp oldWidget) {
super.didUpdateWidget(oldWidget);
if (this.mounted){
if(oldWidget.videoUrl != widget.videoUrl) {
try {
this.initialize();
}catch(e){
}
}
}
}
#override
void dispose() {
_videoPlayerController.dispose();
_chewieController.dispose();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
super.dispose();
}
#override
Widget build(BuildContext context) {
if(widget.autoPlay) {
_videoPlayerController.play();
}
return new Container(
child: new Center(
child: new Chewie(
controller: _chewieController,
)
),
);
}
}
My question is what could be causing this error and how to fix this. I also want to make the video player go fullscreen when the orientation of the device is landscapeleft or landscaperight.
Let me know if I should add anything else in here.
Thank you.
Edit:
I have fixed the exception. Thanks to Ibrahim Karahan! I need help with making the video player go full screen when the device is turned landscape. Thanks again.