I have followed this guide: https://medium.com/flutter-community/flutter-vi-navigation-drawer-flutter-1-0-3a05e09b0db9
trying to replicate the drawer especially. However, I run into an error with the static constant in my Routes.dart file.
the codes looks like this:
in my lib/routes/routes.dart file:
import 'package:book_club/main.dart';
class Routes {
static const String Profile = ProfilePage.routeName;
static const String BookClub = BookClubPage.routeName;
static const String Library = LibraryPage.routeName;
static const String Search = SearchPage.routeName;
static const String Store = StorePage.routeName;
}
It gives me the following two errors:
error: Const variables must be initialized with a constant value. (const_initialized_with_non_constant_value at [book_club] lib/Routes/routes.dart:2)
error: Undefined name 'ProfilePage'. (undefined_identifier at [book_club] lib/Routes/routes.dart:2)
Anyone who can help me understand what I have done wrong? Tried going through the article several times but cannot find my misstake. I am a complete beginner in programming so hoping that there is an easy and obvious way to fix this :)
Using android studio if that makes a difference.
first import the ProfilePage package,
and
static const String Profile = ProfilePage.routeName; here the routeName of ProfilePage has to be static const as well, which means value of the variable should be known before compiling
class AClass{
static const yadu = '';
}
class BClass{
static const y = AClass.yadu;
}
Related
I'm trying to use a version of nested classes to make a tree of constant strings throughout my app in Flutter. I'd like them to be nested in order to find const strings quickly as the app grows, but still have the additional 'speed' of using the const keyword for Text() widgets.
However, I'm having a hard time trying to use them in const Text() widgets.
Here's a sample:
class Strings {
static const String ok = 'OK';
static TechnicianStrings technicianStrings = TechnicianStrings();
}
class TechnicianStrings {
TechnicianStrings();
final String createTech = 'Create Technician';
final String technician = 'Technician';
}
Throughout the app, I'd like to use these constant Strings as so:
const Text(Strings.ok), // <-- this works
const Text(Strings.technicianStrings.technician), //<-- only works without 'const'
const Text(Strings.technicianStrings.createTech), //<-- only works without 'const'
However, I get an error of "Arguments of a constant creation must be constant expressions" when I use the const keyword for the text widgets.
I've tried to use varying "const and static" names for the members of TechnicianStrings, and I get errors such as "invalid Constant" for the text widget. I also defined TechnicianStrings as static const, and got an error of 'Constant variables must be initialized with a constant value' for the line:
static const TechnicianStrings technicianStrings = TechnicianStrings();
Is there a way to use such a nested class structure hand in hand with const Text() widgets?
You need a constant constructor in TechnicianStrings.
class Strings {
static const String ok = 'OK';
static const TechnicianStrings technicianStrings = TechnicianStrings();
}
class TechnicianStrings {
const TechnicianStrings(); // <---
final String createTech = 'Create Technician';
final String technician = 'Technician';
}
Check these two examples:
static const inside of class:
class SessionStorage {
static const String _keySessionExist = 'storage.key';
}
Just a const outside of the class:
const String _keySessionExist = 'storage.key';
class SessionStorage {
}
Is there any difference or implications between having a static const variable inside of a class or just having it declared as const outside of it in Dart?
Maybe the compiled code changes?
Which one is more performant?
Which one should we follow if the variable is private to the file?
The declaration for cons must be using const. You have to declare it as static const rather than just const.
static, final, and const mean entirely distinct things in Dart:
static means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies members.
final means single-assignment: a final variable or field must have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies variables.
const has a meaning that's a bit more complex and subtle in Dart. const modifies values. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, const means that the object's entire deep state can be determined entirely at compile time and that the object will be frozen and completely immutable.
Const objects have a couple of interesting properties and restrictions:
They must be created from data that can be calculated at compile time. A const object does not have access to anything you would need to calculate at runtime. 1 + 2 is a valid const expression, but new DateTime.now() is not.
They are deeply, transitively immutable. If you have a final field containing a collection, that collection can still be mutable. If you have a const collection, everything in it must also be const, recursively.
They are canonicalized. This is sort of like string interning: for any given const value, a single const object will be created and re-used no matter how many times the const expression(s) are evaluated. In other words:
getConst() => const [1, 2];
main() {
var a = getConst();
var b = getConst();
print(a === b); // true
}
I think Dart does a pretty good job of keeping the semantics and the keywords nicely clear and distinct. (There was a time where const was used both for const and final. It was confusing.) The only downside is that when you want to indicate a member that is single-assignment and on the class itself, you have to use both keywords: static final.
Also:
I suggest you to have a look at this question
What is the difference between the "const" and "final" keywords in Dart?
Is there any difference or implications between having a static const variable inside of a class or just having it declared as const outside of it in Dart?
The obvious difference is that the static version must be referenced with the class name. Other than the change in name resolution, the should be the same.
Maybe the compiled code changes?
Which one is more performant?
They're both compile-time constants. There shouldn't be any difference.
Which one should we follow if the variable is private to the file?
If you want something that's private to a Dart library (which usually means the file), then prefix it with _. It doesn't matter whether it's global or static.
In consts class, I have declared this
Consts
static const URL = "";
In login bloc, after login successfully,server will return the url to me, and I assign the url to this variable.
Response user =
await _repo.getLogin(context, email, password);
var baseResponse = UserResponse.fromJson(user.body);
if (baseResponse.status == 101) {
Consts.URL = baseResponse.url;
}
In repo class, assume I have 5 methods, I need to use the url in consts class.Is it a good solution and possible?
Future create(){
try{
var request = http.MultipartRequest('POST',Uri.parse(Consts.URL));
}catch(e){
}
}
You cannot assign a value to a const during run time since const is a compile-time constant.
Please refer documentation on https://dart.dev/guides/language/language-tour#final-and-const
Final and const If you never intend to change a variable, use final or
const, either instead of var or in addition to a type. A final
variable can be set only once; a const variable is a compile-time
constant. (Const variables are implicitly final.) A final top-level or
class variable is initialized the first time it’s used.
I am learning Flutter(Mostly from Youtube) & while learning it I have seen many instructor have used a statement like this,
final SomeClass someVariable = const SomeClass(withSomeValue);
What bothers me that why do we need to use const keyword after the assignment operator there since we already made it a final & I already know that final keyword is used to define a constant variable. So what does const signifies here?
It's a memory optimization possible with immutable objects.
const instances are shared:
final a = const Whatever();
final b = const Whatever();
print(identical(a, b)); // true
In this snippet, both a and b share the same object instance, so it is allocated only once.
Here, the object allocation, takes place just once, so it is good for performance.
final Test test = const Test();
final Test test2 = const Test();
Here it takes place twice.
final Test test = Test();
final Test test2 = Test();
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.