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

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);
}
}

Related

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)

Flutter LateError on controller has not been initialized

When I try to call my widget it's showing an error on the controller that _controller is not initialized I try to set it in initstate.
class CameraApp extends StatefulWidget {
final dynamic loadingWidget;
CameraApp(this.loadingWidget);
_CameraAppState createState() => _CameraAppState();
}
class _CameraAppState extends State<CameraApp> with WidgetsBindingObserver {
late List<CameraDescription> _cameras;
late CameraController _controller;
int _selected = 0;
#override
void initState() {
CameraController _controller;
super.initState();
setupCamera();
WidgetsBinding.instance!.addObserver(this);
}
#override
void dispose() {
WidgetsBinding.instance!.addObserver(this);
_controller.dispose();
super.dispose();
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) async {
if (_controller == null || !_controller.value.isInitialized) {
return;
}
if (state == AppLifecycleState.inactive) {
_controller.dispose();
} else if (state == AppLifecycleState.resumed) {
setupCamera();
}
}
#override
Widget build(BuildContext context) {
if (_controller == null) {
if (widget.loadingWidget != null) {
return widget.loadingWidget;
} else {
return Container(
color: Colors.black,
);
}
} else {
return CameraPreview(_controller);
}
}
Future<void> setupCamera() async {
await [
Permission.camera,
].request();
_cameras = await availableCameras();
var controller = await selectCamera();
setState(() => _controller = controller);
}
selectCamera() async {
var controller =
CameraController(_cameras[_selected], ResolutionPreset.max);
await controller.initialize();
return controller;
}
toggleCamera() async {
int newSelected = (_selected + 1) % _cameras.length;
_selected = newSelected;
var controller = await selectCamera();
setState(() => _controller = controller);
}
}
I am showing this camera on some widgets but don't figure out how to solve this issue. Maybe because of late it's causing an issue. Showing every time when its load i also try to add contoller.initialize(); in initstate but not working
LateError means a variable declared using the late keyword has not been initialized by the time you try to use it, as a general rule, I try to never use the late keyword unless there is no better way to achieve what I want because it tends to cause hard to find errors.
So you have two late variables, _controller and _cameras.
both initialize on the setupCamera method, which is asynchronous and gets called on initState, but the problem I believe is that initState does not wait for them to finish initializing before running build, where you try to read _controller and, because you have yet to assign it, you get a LateError.
If my assertion is correct, it should be a relatively simple fix:
from:
late List<CameraDescription> _cameras;
late CameraController _controller;
to:
List<CameraDescription> _cameras = []; // could also be null I guess.
CameraController _controller = null;
You already have null checks everywhere in case _controller is null, I believe you should take advantage of that so that if build runs before _controller has a value assigned, you get the loading widget.
CameraController _controller = null;
It can't take null value.

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

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
}

Getting "Missing concrete implementation of State.build" Error in Flutter

I am receiving the error "Missing concrete implementation of State.build" when attempting to run this code for Angela Yu's FLutter course:
import 'package:flutter/material.dart';
import 'package:clima/services/location.dart';
import 'package:http/http.dart';
class LoadingScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _LoadingScreenState();
}
}
class _LoadingScreenState extends State<LoadingScreen> {
#override
void initState() {
super.initState();
getLocation();
}
}
void getLocation() async {
Location location = Location();
await location.getCurrentLocation();
print(location.latitude);
print(location.longitude);
}
void getData() async {
Response response = await get(
'https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=439d4b804bc8187953eb36d2a8c26a02');
print(response);
#override
Widget build(BuildContext context) {
return Scaffold();
}
}
I have tried the responses related to this question:
missing concrete implementation of state.build
...but have not had any success. Any insight as to what I'm doing wrong would be very much appreciated.
enter code hereYou have a extra } after
#override
void initState() {
super.initState();
getLocation();
}
Delete it
And another missed above
#override
Widget build(BuildContext context) {
return Scaffold();
}
Check your { }
Check your {}. This error mainly comes due to the missing of {} or using extra {}.

Could not called initState and update (riverpod state_notifier)

Problem
I'm using riverpod and state_notifier.
The initState() and update() that StateNotifier has are called and No. The other member functions can be called successfully. However, other member functions can be called successfully.
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:riverpod_todo_list/todo_list_notifier.dart';
import 'package:riverpod_todo_list/todo_list_state.dart';
void main() {
print('start~~');
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends HookWidget {
// ...
}
final todoListProvider = StateNotifierProvider((_) => TodoListNotifier());
class MyHomePage extends HookWidget {
final _controller = TextEditingController();
final todoListNotifier = useProvider(todoListProvider);
final TodoListState _todoListState =
useProvider(todoListProvider.state.select((value) => value));
//...
import 'package:riverpod_todo_list/todo.dart';
import 'package:riverpod_todo_list/todo_list_state.dart';
import 'package:state_notifier/state_notifier.dart';
import 'package:uuid/uuid.dart';
class TodoListNotifier extends StateNotifier<TodoListState> with LocatorMixin {
TodoListNotifier() : super(const TodoListState());
Uuid _uuid = Uuid();
// could not run.
#override
void initState() {
super.initState();
print('init state~~~');
}
// could not run.
#override
void update(Locator watch) {
super.update(watch);
print('update');
}
// could run.
void add(String title) {
Todo todo = Todo(id: _uuid.v4(), title: title);
List<Todo> todoList = []..addAll(state.todoList);
todoList.add(todo);
state = state.copyWith(todoList: todoList);
}
// could run.
void toggleStatus(int index) {
List<Todo> todoList = []..addAll(state.todoList);
todoList[index] = state.todoList[index]
.copyWith(completed: !state.todoList[index].completed);
state = state.copyWith(todoList: todoList);
print('changed toggle~~');
}
}
restarted logs
not put initState() and update() logs.
Performing hot restart...
Restarted application in 464ms.
flutter: start~~
The question is already answered on the Github.
LocatorMixin is not supported by Riverpod.
https://github.com/rrousselGit/river_pod/issues/75#issuecomment-671255330
And it's proposed to note it in the document.
In my opinion, LocatorMixin is not needed to use with Riverpod because of ProvidierReference.
final userRepositoryProvider = Provider((ref) => UserRepository());
final userControllerProvider = StateNotifierProvider((ref) {
return UserController(
// Read userRepositoryProvider and create a UserController from the result
repository: ref.watch(userRepositoryProvider),
);
});