Flutter i18n shortcut - flutter

I'm trying to make a function that get my i18n string by passing variable.
String getStringLanguage(context, String key) {
dynamic translation = AppLocalizations.of(context);
String tmp = key.toString();
return translation.key;
}
but I have this error
Class 'AppLocalizationsFr' has no instance getter 'key'.
Receiver: Instance of 'AppLocalizationsFr'
Tried calling: key
I understand why I have this error, but is it possible to force flutter to use my key variable, instead of searching the key constant ?
this is a small part of my AppLocalizations class
abstract class AppLocalizations {
String get email;
}

Try...
1- Import the library
import 'package:intl/intl.dart';
2- Use the function to get the value
Intl.message(translation.key)

Related

Why does it keep saying initialize variable?

Below is the code I wrote. I need to initialize a variable called verificationID for later use. But I keep getting a red squiggly line with the text -
Final variable verificationID must be initialized
Non-nullable instance field vdi must be initialized.
Is this not how you initialize - final [datatype] [name]
I am brand new to flutter and could use any help!
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
enum NumberVerification {
SHOW_MOBILE_FORM_STATE,
SHOW_OTP_FORM_STATE,
}
class LoginScreen extends StatefulWidget {
final String verificationID;
String vdi;
#override
_LoginScreenState createState() => _LoginScreenState();
}
All variables in Dart are getting the value null if nothing else are specified. This is a problem in your case since both verificationID and vdi are specified as non-nullable types (no ? after the type name). So Dart complains about this problem.
Another problem is your final variable which also should be provided a value since this is a read-only variable which can only be assigned a value when initialized.
You therefore need to do:
Change the types to allow null.
Or, provide default value other than null.
Or, make a constructor of your class which gives values to your variables. These values can come from parameters to the constructor.
Because flutter and dart language are null safety. It means you should initialize your variables, and there will be no error regarding this in runtime. So when you write dart codes you must initialize them as follows:
1- In some cases you can init value directly as follows:
final String verificationID = 'value';
2- Or you can get the value from constructor of class.
final String verificationID;
LoginScreen(this.verificationID);
3- And also, you can declare that you will initialize the value later. This way you guarantee that you will initialize the value, so you should use it wisely.
late String verificationID;
verificationID = 'value';
4- Lastly, you may declare a value as nullable. This way, you don't need to initialize the variable directly.
String? verificationID;

A way to read a String as dart code inside flutter?

I want to build a method to dynamically save attributes on a specific object
given the attribute name and the value to save I call the "save()" function to update the global targetObj
var targetObj = targetClass();
save(String attribute, String value){
targetObj.attribute = value;
print(targetObj.attribute);
}
But I'm getting the following error:
Class 'targetClass' has no instance setter 'attribute='.
Receiver: Instance of 'targetClass'
Tried calling: attribute="Foo"
The only thing that I can think of is that "attribute" due to being type String results in an error.
That lead me to think if there is a way to read a String as code, something like eval for php.
As #Randal mentioned, you cannot create class..method at runtime. Still, you can try something like this.
A certain class
class Foo {
dynamic bar1;
dynamic bar2;
// ...
}
Your save method
save(Foo fooObject, String attribute, dynamic value) {
if ("bar1" == attribute) fooObject.bar1 = value;
else if ("bar2" == attribute) fooObject.bar2 == value;
// ...
}
Dart (and thus flutter) does not have a way to compile and execute code at runtime (other than dart:mirrors, which is deprecated). You can build additional code that derives from other code using the various builder mechanisms, although it can be rather complicated to implement (and use!).

The argument type 'Future<xxx>' can't be assigned to the parameter type 'FutureOr<xxx>' Flutter & Dart

This code works if I use String as the type, but not if I use a class.
Calling code:
Future<Card> getCard() {
return Future.value(currPack.getCard());
}
Here is the getCard method:
Future<Card> getCard() async {
return Card("a", "b");
}
Here is the Card class:
class Card {
String question = "";
String answer = "";
Card(String question, String answer) {
this.question = question;
this.answer = answer;
}
}
When I use the Card class, I get a warning message saying:
The argument type 'Future<Card>' can't be assigned to the parameter type 'FutureOr<Card>'
If I change the return type from Card to String and set the method to return a string it works fine.
Turns out there is a class in material design called Card: 'package:flutter/src/material/card.dart'.
The first bit of code is part of a screen that imports material.dart (import 'package:flutter/material.dart').
The other code is from a standalone class that doesn't import material.dart, but does reference the local card class (import 'package:flashcards/modules/Card.dart';).
So to sum it up: the error was caused by having references to two classes with the same name and not distinguishing between the two.

Dart: How to use the dot notation, uncaught TypeError Problem

I have the following code in dart, which decodes a string into a JSON object.
import 'dart:convert';
void main(){
var stringValue = "{\"last_supported\": \"2.00\", \"current\": \"2.00\"}";
var newValue = json.decode(stringValue);
print(newValue["last_supported"]);
}
The above code works fine, but when I change print statement to:
print(newValue.last_supported);
It gives me the following exception:
Uncaught TypeError: C.C_JsonCodec.decode$1(...).get$last_supported is not a function
Is it possible to use dot annotation to access properties, and how?
I'm guessing you come from a java-script background.
in dart object keys cannot be accessed through the . dot notation.
rather they are accessed like arrays with ['key_name'].
so that's why this line doesn't work
print(newValue.last_supported)
and this one does
print(newValue["last_supported"]);
dot notation in dart only works on class instances, not Map (similar to JavaScript objects).
look at the following :
class User {
final String name;
final int age;
// other props;
User(this.name, this.age);
}
Now when you create a new user object you can access its public attributes with the dot notation
final user = new User("john doe", 20); // the new keyword is optional since Dart v2
// this works
print(user.name);
print(user.age);
// this doesn't work because user is an instance of User class and not a Map.
print(user['name]);
print(user['age]);
For more about the new keyword you can read the v2 release notes here.

Unable to use generic function in a generic function

I have the following class in my code
abstract class DatabaseKey<T> implements Built<DatabaseKey<T>, DatabaseKeyBuilder<T>> {
DatabaseKey._();
factory DatabaseKey([void Function(DatabaseKeyBuilder<T>) updates]) = _$DatabaseKey<T>;
String get name;
}
Then, I define the following generic typedef function:
typedef ObserveDatabaseEntity = Observable<DatabaseEntity<T>> Function<T>(DatabaseKey<T> key);
But, when I try to use it as follows, the code has an error.
static ObserveConfigurationValue observe(
GetConfigurationState getState,
ObserveDatabaseEntity observeDatabaseEntity,
) {
assert(getState != null);
assert(observeDatabaseEntity != null);
return <KT>(ConfigKey<KT> key) {
return Observable.just(getState())
.flatMap((state) {
final dbKey = _databaseKeyFromConfig<KT>(key);
return observeDatabaseEntity(dbKey)
.map(_configValueFromDatabaseEntity);
});
}
}
DatabaseKey<T> _databaseKeyFromConfig<T>(ConfigKey<T> key) {
return DatabaseKey((build) => build
..name = key.value,
);
}
The error I am getting is:
The argument type DatabaseKey can't be assigned to the parameter DatabaseKey.
I see nothing wrong with this code or why it shouldn't work, but maybe my understanding of what can be written in Dart is wrong. What would be the correct way to write this, if possible at all?
EDIT#1:
Note:
The typedef ObserveDatabaseEntity is in one file
The static ObserveConfigurationValue observe(GetConfigurationState getState, ObserveDatabaseEntity observeDatabaseEntity) is is another file
From playing around, it seems that placing them in a single file, the error disappears.
Still, I believe that this should work in separate files as well,
This error looks like an import mismatch.
In dart, you can import file either through relative path or package.
import 'lib/some_file.dart'; //relative
import 'package:myapp/lib/some_file.dart'; //package
There's really no better way but once you choose one, you have to stick to it. If you don't (meaning you have imported a file using a package import and the same file elsewhere with a relative path) Dart will place them in two different namespaces and think they are two different classes.