Flutter md link not loading md file - flutter

I am using the flutter_markdown widget to display help info in my app.
Inside an md file I am using the link to another md file. Both md files are defined in the 'assets' list in the pubspec.yml file
### [Overview](resource:asset/doc/overview.md) / Match Screen ###
Then I'm using the 'onTapLink' event handler to capture the users tap on the link to reset the markup widget to display the new md file like...
Future<String> _getData(String aFileName) async{
return rootBundle.loadString(aFileName);
}
#override
Widget build(BuildContext context) {
// get
return Scaffold(
appBar: AppBar(title: Text('Help')),
body: FutureBuilder<String>(
future: _dataFuture,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return Markdown(data: snapshot.data!, onTapLink: (text,href,title) {
setState(() {
_dataFuture = _getData(href!);
});
},);
}
return Center(
child: CircularProgressIndicator(),
);
}),
);
}
However, the onTapLnk code is causing an exception where it can't load the md file name passed in 'hef'
E/flutter ( 7261): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Unable to load asset: resource:asset/doc/overview.md
E/flutter ( 7261): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:237:7)
E/flutter ( 7261): <asynchronous suspension>
E/flutter ( 7261): #1 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:72:27)
E/flutter ( 7261): <asynchronous suspension>
E/flutter ( 7261):
Any suggestions?
Through testing I can separately display both md files, so its nothing to do with faulty asset definition in the pubspec.yml file.

Solved it
The link definition in the md file should be
### [Overview](asset/doc/overview.md) / Match Screen ###
not
### [Overview](resource:asset/doc/overview.md) / Match Screen ###

Related

In Flutter MaterialApp, using Provider inside LocaleResolutionCallback has an error

In my flutter project, I selected riverpod_hook for DI.
In order to change the language setting of the application according to the language setting of the mobile device, I wrote the code as follows.
// app.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
class Application extends ConsumerWidget {
const Application({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
return MaterialApp(
theme: defaultTheme,
localizationsDelegates: Resource.localizationsDelegates,
supportedLocales: Resource.supportedLocales,
localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) {
if (supportedLocales.any((element) => locale?.languageCode.contains(element.toString()) == true)) {
ref.watch(localeCodeProvider.notifier).state = locale!.languageCode;
return locale;
}
return const Locale('ko', '');
},
routes: {
homePageRoutes: (_) => const HomePage(),
detailPageRoutes: (_) => const DetailPage(),
},
);
}
}
import 'package:hooks_riverpod/hooks_riverpod.dart';
final localeCodeProvider = StateProvider<String>((ref) => 'en');
When I run this code, this error was occurred.
E/flutter ( 3747): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Tried to modify a provider while the widget tree was building.
E/flutter ( 3747): If you are encountering this error, chances are you tried to modify a provider
E/flutter ( 3747): in a widget life-cycle, such as but not limited to:
E/flutter ( 3747): - build
E/flutter ( 3747): - initState
E/flutter ( 3747): - dispose
E/flutter ( 3747): - didUpdateWidget
E/flutter ( 3747): - didChangeDepedencies
E/flutter ( 3747):
E/flutter ( 3747): Modifying a provider inside those life-cycles is not allowed, as it could
E/flutter ( 3747): lead to an inconsistent UI state. For example, two widgets could listen to the
E/flutter ( 3747): same provider, but incorrectly receive different states.
E/flutter ( 3747):
E/flutter ( 3747):
E/flutter ( 3747): To fix this problem, you have one of two solutions:
E/flutter ( 3747): - (preferred) Move the logic for modifying your provider outside of a widget
E/flutter ( 3747): life-cycle. For example, maybe you could update your provider inside a button's
E/flutter ( 3747): onPressed instead.
E/flutter ( 3747):
E/flutter ( 3747): - Delay your modification, such as by encasuplating the modification
E/flutter ( 3747): in a `Future(() {...})`.
E/flutter ( 3747): This will perform your upddate after the widget tree is done building.
I can see from the error message that the error occurred because the provider watch was used inside the build function.
However, I unwillingly need to utilize that localeResolutionCallback attribute because I want to set the language setting value of the mobile device and set the language across the application.
In this situation, could I get an appropriate solution on how to use the provider?
Try if calling WidgetsBinding.instance.addPostFrameCallback would work, somethign like this:
if (supportedLocales.any((element) => locale?.languageCode.contains(element.toString()) == true)) {
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.watch(localeCodeProvider.notifier).state =
locale!.languageCode;
});
return locale;
}
What it does - it allows your build to complete; and then changes the provider - which will most likely call another build.

Unhandled Exception: Null check operator used on a null value in flutter

I hope you are well, I will give you a bit of context about my problem...
I really don't know why this error happens and I've seen many similar publications but they haven't worked for me.
I'm new to flutter and I'm working on an app, but when the user wants to log out, the app crashes and shows the following error:
E/flutter (12659): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter (12659): #0 StatefulElement.state
package:flutter/…/widgets/framework.dart:4999
E/flutter (12659): #1 Navigator.of
package:flutter/…/widgets/navigator.dart:2543
E/flutter (12659): #2 Navigator.pushReplacement
package:flutter/…/widgets/navigator.dart:2105
E/flutter (12659): #3 MainCoordinator.logoutNavigation
package:domicilios/…/MainCoordinator/MainCoordinator.dart:62
E/flutter (12659): #4 UserActions.signOut.<anonymous closure>.<anonymous closure>
package:domicilios/…/View/ProfileTab.dart:222
E/flutter (12659): <asynchronous suspension>
This is the code that generates this error, I hope you can help me, thank you very much for your attention.
this is the class:
extension UserActions on _ProfileTabState {
void signOut(BuildContext context) {
AlertView.showAlertDialog(
model: AlertViewModel(
context,
const AssetImage('assets/logout.png'),
'Cierre de sesión en curso',
"¿Desear salir de la sesión actual?",
'Cerrar sesión',
"Cancelar", () {
_profileTabViewModel
.signOut()
.then((value) => coordinator.logoutNavigation(context: context));
}, () {
Navigator.pop(context);
}));
}
}
That's how I call it in the code:
onTap: () => signOut(context),
This is most likely due to the widget being unmounted before navigating.
You can check if the widget is mounted before navigating.
if (mounted) {
_profileTabViewModel.signOut().then((value) {
if (mounted) {
coordinator.logoutNavigation(context: context);
}
});
}
Also,
if(mounted){
Navigator.pop(context);
}

How can I do contextless navigation in order to move to a maintenance screen in Flutter?

I have a Maintenance controller, that initializez an observable variable, and whenever that variable is true, it navigates to a maintenance screen, and when the variable gets set to false it navigates back as follows:
class MaintenanceController extends GetxController {
RxBool isMaintenance = false.obs;
#override
onInit() {
super.onInit();
ever(
isMaintenance,
(_) => {
if (isMaintenance.value) {Get.offNamed(Routes.maintenance)} else {Get.offNamed(Routes.splash)}
});
}
}
Everything works fine, but I get the following exception in the logs:
flutter: You are trying to use contextless navigation without
a GetMaterialApp or Get.key.
If you are testing your app, you can use:
[Get.testMode = true], or if you are running your app on
a physical device or emulator, you must exchange your [MaterialApp]
for a [GetMaterialApp].
flutter:
#0 GetNavigation.global (package:get/get_navigation/src/extension_navigation.dart:1094:7)
#1 GetNavigation.offNamed (package:get/get_navigation/src/extension_navigation.dart:629:12)
#2 MaintenanceController.onInit.<anonymous closure> (package:n_app/src/screens/maintenance/maintenance_controller.dart:17:85)
#3 ever.<anonymous closure> (package:get/get_rx/src/rx_workers/rx_workers.dart:69:44)
#4 GetStream._notifyData (package:get/get_rx/src/rx_stream/get_stream.dart:47:21)
#5 GetStream.add (package:get/get_rx/src/rx_stream/get_stream.dart:97:5)
#6 RxObjectMixin.value= (package:get/get_rx/src/rx_types/rx_core/rx_impl.dart:105:13)
#7 MaintenanceController.subscribe.<anonymous closure> (package:n_app/src/screens/maintenance/maintenance_controller.dart:29:21)
#8 _rootRunUnary (dart:async/zone.dart:1434:47)
#9 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
#10 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
#11 _Bufferi<…>
flutter: ----------------------------------------------------
app.dart:
GetMaterialApp(
debugShowCheckedModeBanner: false,
locale: Get.find<LocalizationController>().deviceLocale,
getPages: Routes.routes,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
unknownRoute: Routes.getNotFound,
initialRoute: GetPlatform.isWeb ? Routes.initial : Routes.splash,
theme: Get.find<ThemeController>().themeData,
navigatorKey: NavigationService.navigatorKey,
);
I tried to add the navigatorKey: Get.key and use navigatorKey.currentState!.pushNamed(routeName); to navigate, but the currentState is always null. Any advice?
You have to use GetMaterialApp instead of MaterialApp for the contextless navigation to work in GetX.
Replace
MaterialApp(home: somePage());
with
GetMaterialApp(home: somePage());
Adding navigatorKey: Get.key to the GetMaterialApp and continuing to use Get.offNamed(...) instead of navigatorKey.currentState!.pushNamed(routeName); worked.

flutter scheduler callback errors?

So I'm running through some tutorials for Flutter Animation, and I had to use something called a Post Frame callback to ensure that function didn't run until after the build function, like so (with the function in question displayed):
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_addTrips();
});
}
void _addTrips() {
// get data from db
List<Trip> _trips = [
Trip(title: 'Beach Paradise', price: '350', nights: '3', img: 'beach.png'),
Trip(title: 'City Break', price: '400', nights: '5', img: 'city.png'),
Trip(title: 'Ski Adventure', price: '750', nights: '2', img: 'ski.png'),
Trip(title: 'Space Blast', price: '600', nights: '4', img: 'space.png'),
];
The build function (within the same initState) looks like this:
#override
Widget build(BuildContext context) {
return AnimatedList(
key: _listKey,
initialItemCount: _tripTiles.length,
itemBuilder: (context, index, animation) {
return SlideTransition(
child: _tripTiles[index],
position: animation.drive(_offset)
);
}
);
}
The items on the list fail to populate when I run the code. The error that I'm getting in the run panel is the following with the stack included:
Exception caught by scheduler library
The following assertion was thrown during a scheduler callback:
'package:flutter/src/widgets/animated_list.dart': Failed assertion: line 963 pos 12:
'itemIndex >= 0 && itemIndex <= _itemsCount': is not true.
Either the assertion indicates an error in the framework itself, or we should provide
substantially more information in this error message to help you determine and fix the
underlying
cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md
When the exception was thrown, this was the stack:
#2 SliverAnimatedListState.insertItem
(package:flutter/src/widgets/animated_list.dart:963:12)
#3 AnimatedListState.insertItem
(package:flutter/src/widgets/animated_list.dart:484:42)
#4 _TripListState._addTrips.<anonymous closure>
(package:ninja_trips/shared/tripList.dart:33:29)
#5 List.forEach (dart:core-patch/growable_array.dart:403:8)
#6 _TripListState._addTrips (package:ninja_trips/shared/tripList.dart:31:12)
#7 _TripListState.initState.<anonymous closure>
(package:ninja_trips/shared/tripList.dart:18:7)
#8 SchedulerBinding._invokeFrameCallback
(package:flutter/src/scheduler/binding.dart:1143:15)
#9 SchedulerBinding.handleDrawFrame
(package:flutter/src/scheduler/binding.dart:1088:9)
#10 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure>
(package:flutter/src/scheduler/binding.dart:863:7)
(elided 13 frames from class _AssertionError, class _RawReceivePortImpl, class _Timer,
dart:async, and dart:async-patch)
The tutorial in question didn't seem to anticipate this as a possibility and I'm pretty stumped so far. Any ideas?
Thanks,
ATD

Flutter : firebase MissingPluginException

I'm having this problem about flutter and firebase(realtime-database).
Unhandled Exception: MissingPluginException(No implementation found for method Query#observe on channel plugins.flutter.io/firebase_database)
Here is the error in terminal
error
// error message
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method Query#observe on channel plugins.flutter.io/firebase_database)
#0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
<asynchronous suspension>
#1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
#2 Query._observe.<anonymous closure> (package:firebase_database/src/query.dart:50:38)
#3 _runGuarded (dart:async/stream_controller.dart:820:24)
#4 _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:215:7)
#5 _ControllerStream._createSubscription (dart:async/stream_controller.dart:833:19)
#6 _StreamImpl.listen (dart:async/stream_impl.dart:475:9)
#7 Stream.first (dart:async/stream.dart:1254:25)
#8 Query.once (package:firebase_database/src/query.dart:84:55)
#9 _IoTState.initState (package:flutter_try_iot/main.dart:36:13)
#10 StatefulElement._f<…>
I'm trying to get data from firebase to display in flutter app.
Here is my code main.dart
class _IoTState extends State<IoT> {
final getIot = FirebaseDatabase.instance.reference();
final getData = FirebaseDatabase.instance.reference().child('xxx-xxx');
String temperatue = "0";
String illuminance = "0";
List<String> temp = [];
List<String> light = [];
#override
void initState(){
getData.once().then((DataSnapshot snapshot){
if (snapshot.value == null) {
print("Item doesn't exist in the db");
} else {
print("Item exists in the db");
}
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF7ACADA),
title: Text(
"IoT ZigBee Simulation",
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF1A1244)
),
),
),
body: Column(
),
);
}
}
pubspec.yaml
firebase_core: ^0.4.5
firebase_database: ^3.1.6
flutter_icons: ^1.1.0
fl_chart: ^0.10.1
I follow instructions to add ios to firebase .ios add firebase
no issues found by flutter doctor
I follow other peoples suggestion to do flutter clean & flutter packages get, but still not able to fix this problem
https://github.com/flutter/flutter/issues/13971
terminal
Also pop up a window telling me The file “Runner.xcworkspace” has been modified by another application" everytime I execute flutter clean/ flutter packages get
I successfully connect to firebase yesterday, but after I close my simulator I start to receive error message
success picture
Please give me some solution or advice to fix this problem, thanks.
Please tell me if I need to provide additional information