passing dynamic strings to AppLocalizations.of(context)! in Flutter - flutter

right now Im working in App using Flutter and I have 4 different languages, I use json (arb files) for localization (translation)
I need to pass different string values which app fetch them using API's as shown in example below
AppLocalizations.of(context)!snapshot.data![index].state_pickup[0]
however "AppLocalizations.of(context)!" doesn't fetch the return data from snapshot.data![index].state_pickup[0] and instead it looks for it as string and tries to search for match string name in AppLocalization.dart class?
Any idea how I can pass dynamic string arguments to AppLocalizations.of(context)!?

What you are trying to do, invoking a method by its name at runtime, is called reflection, and this is not supported by Flutter natively (though there are packages that try to emulate this, but I have no experience with them).
What will work for you, even though it might be tedious, is manually mapping your value from the API to the corresponding method from AppLocalizations.of(context).
String localizedString = getLocalizedString(snapshot.data![index].state_pickup[0], context);
String getLocalizedString(String key, BuildContext context) {
switch (key) {
case "possible_api_value_1":
return AppLocalizations.of(context)!.possibleApiValue1;
case "possible_api_value_2":
return AppLocalizations.of(context)!.possibleApiValue2;
...
}

Related

How can I apply dart extension methods in the Flutter Logging library?

I am trying logging library in my flutter project. They have some good record messages (e.g. record.name, record.message, etc.) For my project, I want to extend by using dart extension methods this package to add some more record message (e.g. record.version, record.eventName, etc.). As a beginner in dart, I am not sure completely how to do that?
Here is an example that I tried but failed.
extension CustomLog on LogRecord {
String version(LogRecord version) => "1.0";
String eventName(LogRecord eventName) => "userNameChangedEvent";
}
Please provide me some suggestions/examples how can I extend any package and use it on my own.
Logging does not support extending (with extension) the LogRecord to add custom fields.
You can pass all your custom info as an class object in object param and retrieve it later.
Something like
class CustomLogAttributes {
final String version;
final String eventName;
CustomLogAttributes(this.version, this.eventName);
}
then
log.fine("example log message", object: CustomLogAttributes("1.1.0", "example_event");

Flutter intl access string dependent on variables

I use intl in my Flutter app.
I need a string resource that depends on two different user selections.
The name of the resource looks like resoucename_<selection1>_<selection2>.
The user selections are taken from a dropdown field.
To prevent checking a lot of cases, on native Android I got the string using Java Reflection:
String resName = "resource_" + userSelection1 + "_" + userSelection2;
Field idField = R.string.class.getDeclaredField(resName);
String text = getActivity().getResources().getText(elementart_resource_id)
Is there a way to implement this in dart or is there even a more elegant solution to getting a string dependent on the user's selection?

All string data appears as "Instance of" when i print

recently i made a couple of form pages( text input,radio button, that kind of stuff), and they used to work pretty well. I came back to them after working in another part of the app, and realize that it doesn't work anymore.
I checked a couple of things and realized that all text input data comes as "Instance of thing". So when i send the data to the backend and check it, it appears as null. As far as i know this means that the string data the user input is not being saved as a string inside my variables, but as instances and that's why it doesn't work.
Any ideas as to why this happened? As far as i remember i didn't change anything in these pages.
I'm using provider to maintain the data locally.
If snippets of code are needed please ask.
Most probably if you are getting "Instance of thing" & also null, then you need to await on your data.
class YourClass {
int yourVariable = 0;
String anotherVariable = "string";
#override
String toString() {
return "YourVariable : $yourVariable , AnotherVariable : $anotherVariable";
}
}
You have to override the toString() method and return your objects like above and call toString() method when you print the object

How to cache a value returned by a Future?

For my Flutter app I'm trying to access a List of Notebooks, this list is parsed from a file by the Api. I would like to avoid reading/parsing the file every time I call my notebooks getter, hence I would like something like this:
if the file had already been parsed once, return the previously parsed List<Note> ;
else, read and parse the file, save the List<Note> and returns it.
I imagine something like this :
List<Notebook> get notebooks {
if (_notebooks != null) {
return _notebooks;
} else {
return await _api.getNotebooks();
}
}
This code is not correct because I would need to mark the getter async and return a Future, which I don't want to. Do you know any solution for this problem, like caching values ? I also want to avoid initializing this list in my app startup and only parse once the first time the value is needed.
you can create a singleton and you can store the data inside a property once you read it, from next time onwards you can use the same from the property.
You can refer this question to create a singleton
How do you build a Singleton in Dart?

How to use Strings to access class members in Flutter

I want to set use Strings from an API as Fontawesome icons. I have added the font_awesome_flutter plugin.
I need to store the icon name in a variable and then create an object from it. I would imagine it to like this:
String iconfromApi = 'suitcase';
Icon(FontAwesomeIcons.iconfromApi);
As described here, you would need have access to the dart:mirrors pacakage, which is not avaible in Flutter.
A solution that would work in Flutter is creating a helper method. This means that you will have to code in cases for all icon names you want to use. If you do not want to write all of that by hand, you can take a look at a package like reflectable as mentioned in the GitHub comment or potentially source_gen or build_runner, however, I am not sure if the latter two are well suited.
Anyways, what you could also write by hand is a helper function like this:
IconData fontAwesomeIconFromString(String name) {
switch (name) {
case 'suitecase':
return FontAwesomeIcons.suitecase;
case 'gamepad':
return FontAwesomeIcons.gamepad;
// ...
}
}
In your code, you can now use it like this:
String iconfromApi = 'suitcase';
Icon(fontAwesomeIconFromString(iconFromApi));