Here's a code:
const bool a = const bool.fromEnvironment("true");
print(a); // false
Yes, default value is false by default. What should I do that a will be true, without using default value? And what is the string parameter? is it a key maybe?
What are you trying to achieve?
Setting a to true can be done as const a = true;.
The bool.fromEnvironment function allows you to look up defined named string properties that can be added at the command line when compiling, or which may be defined by the platform you are compile for/running on. So does String.fromEnvironment and int.fromEnvironment.
One set of such platform properties are dart.library.* which are set to true for each dart:* library that the platform supports.
So, to print something other than false, you can do:
print(const bool.fromEnvironment("dart.library.core"));
That one is pretty boring since all platforms support dart:core.
You can check the availability of other libraries as:
const bool supportsMirrors = bool.fromEnvironment("dart.library.mirrors");
const bool isJavaScript = bool.fromEnvironment("dart.library.js");
Or, you can supply a value on the command line when compiling. Let's use the dart stand-alone VM as an example. Write the following script script.dart:
void main() {
print(const bool.fromEnvironment("my-fancy-thing"));
}
If you run it as dart script.dart it prints false.
If you run it as dart -Dmy-fancy-thing=true script.dart it prints true.
Related
Is there a construct that communicates to the type checker a function's post-condition?
For example, in typescript it is possible to say
function assertIsNumber(value: any): asserts value is number {
if (typeof value !== 'number') {
throw new TypeError();
}
}
I would like to be able to do something like the following in dart:
class SomeClass {
int? value;
_checkPreconditions() {
if(value == null) {
throw MyPreconditionError()
}
// ...
}
somefunc() {
_checkPreconditions();
// here we know `value` is a non-null int.
final sum = value + 5;
}
}
I understand I could coerce the value to non-null sum = value! + 5, but I would prefer to allow the function to inform the type checker if possible.
It looks like the type system of Dart is not so powerful. The only thing that looks (from first glance) possible is to create a custom code analyzer package (or search for one that already exists).
Dart annotations don't actually do anything. They provide hints to tools such as the Dart analyzer (usually so that it can generate additional warnings), but they cannot change program behavior. Even if you could convince the analyzer to treat some variables as different types, you still wouldn't be able to compile and run your code.
Annotations can be used by code generation tools, so one possibility might be to generate a statement such as final value = this.value!; automatically. However, that would be a lot of trouble to go through (and would mean that code then would need to use this.value = 42; for assignments and would prevent your code from being analyzed directly).
In dart, why
const cities = ['Delhi', 'UP', 'Noida'];
//error is in this line
cities[0] = 'Mumbai';
is a runtime error, not a compile time error?
See this answer for knowing the implications of const in dart
TLDR const variables are pre compile by dart and you cannot modify them at runtime.
const cities = ['Delhi', 'UP', 'Noida'];
cities[0] = 'Mumbai'; // Throws at runtime
Use final or var instead.
final cities = ['Delhi', 'UP', 'Noida'];
cities[0] = 'Mumbai'; // Works OK
https://www.peachpit.com/articles/article.aspx?p=2468332&seqNum=5#:~:text=EXAMPLE%204.12&text=Unlike%20final%20variables%2C%20properties%20of,its%20values%20cannot%20be%20changed.
Use normal variables, as with constants, you cannot change the value of the list during runtime.
I assume that is done with
var or final, as I'm not a dart master myself.
There currently is no way of indicating in Dart whether a method mutates its object or is guaranteed to leave it alone. (This is unlike, say, C++ where a method could be marked as const to indicate that it does not (visibly) mutate the object.)
Consequently, there isn't a good way for the Dart compiler to know that operator []= shouldn't be allowed to be invoked on a const object, so unfortunately it isn't known that it violates the const-ness of the object until runtime.
I am using this package to set environment variables in flutter in a .env .
To read the variables I have to have this is my main.dart
Future main() async {
await DotEnv().load('.env');
runApp(MyApp());
}
And then read like this
print(DotEnv().env['VAR_NAME']);
From this question, I can also add variables in the build command like this
flutter run --dart-define=APP_VERSION=0.1.2
And then to read the ones set in the build command, I have to do this
const appVersion = String.fromEnvironment('APP_VERSION', defaultValue: 'development');
Is there please a way that I can read variables set in either the .env file or the build command the same way?
I will have the variables in my .env file for local development, and the in dev and prod environments they will be set via commands. So how can I find a way that works for both cases?
Thank you
I am not familiar with the package you mentioned, but a fairly safe bet would be as follows:
Create a singleton class that is responsible for handling environment variables:
final env = Env._();
class Env {
Env._(); // private constructor to prevent accidental initialization
}
Create a method that gets an environment variable from its string, and choose something to default to. IMO I would give precedence to command line args, but that is a matter of taste:
String get(String key, {String defaultValue}) {
final fromFile = DotEnv().env[key];
final fromArgs = String.fromEnvironment(key);
// return the value from command line if it exists
// if not, return the value from .env file
// if still null, return a default
return fromArgs ?? fromFile ?? defaultValue;
}
You can then access the data globally using:
env.get('MY_VARIABLE_NAME', defaultValue: 'hello');
For even more brevity, you can use Dart's callable classes, by renaming get() to call(), and then consume it using:
env('MY_VARIABLE_NAME', defaultValue: 'hello');
The Flutter article for internationalization states the following:
To add support for other languages, an application must specify additional MaterialApp properties, and include a separate package called flutter_localizations.
However, I do not understand what the point of flutter_localizations is and why I "must [...] include" it in my app if I want to add support for other languages.
If I take a look at GlobalMaterialLocalizations, which is what flutter_localizations apparently adds (along with the Widgets and Cupertino versions), I can only find a bunch of seemengly random strings I have never seen translated into a bunch of languages.
I have never seen these strings in my Flutter app.
Do I really need to include flutter_localizations if I want to internationalize my app, i.e. are these strings used anywhere by default?
Actually no.
It depends how you want to implement you internationalization.
You can get current local by:
/// Because of flutter issue
/// https://github.com/flutter/flutter/issues/38323
/// So return `locals[1]` instead of `window.locale`;
var locals = window.locales;
var local = (locals.length > 1) ? locals[1] : window.locale;
Benefit of current flutter_localizations
I think the benefit of this lib is that it also handle the text direction stuff in
The other way
If you only need to handle the Strings' translation, no need to handle text direction(ltr(left to right) or rtl(right to left)):
You handle your strings by the value returned above:
abstract class Strings {
String hello;
factory Strings() // => instance;
{
var locals = window.locales;
var local = (locals.length > 1) ? locals[1] : window.locale;
if (local != null) {
// log('Strings.load(${local.languageCode})');
if (local.languageCode == 'zh') {
return _StringsZH.instance;
}
}
return _StringsEN.instance;
}
}
class _StringsEN implements Strings {
String hello = 'Hello 2019';
_StringsEN._();
static _StringsEN instance = _StringsEN._();
}
class _StringsZH implements Strings {
String hello = '你好 2019';
_StringsZH._();
static _StringsZH instance = _StringsZH._();
}
And use it like
Strings().hello;
I just discovered Chapel's config variable modifier which is great for command line operations. Are there other languages or frameworks that mimic this feature so I don't have to program the filters each time?
The width of all different chapel config-s is indeed unparalleled:
config var VAR = 1; // --VAR=10 sets other value from cmdline
// --VAR 20 sets other value too
config const RHO = 1.23456; // --RHO=0.123456 sets other value from cmdline
// --RHO 0.2468 sets other value too
// --RHO=0.39*VAR sets other value for COMPILER
// based on VAR
config param DBG = false; // -s DBG=true sets other value from cmdline
config type B = uint(8); // -sB='uint(16)' sets other value from cmdline
// -sB='if DBG then uint(32) else uint(16)'
// sets other value for COMPILER
// based on DBG
While there is yet a must to have a compile-time known typing, which is a certain restriction ( for strong-typed, compiled languages both obvious and natural ), still the flexibility of use of these constructs for ad-hoc setup of an adaptive run-time configurable behaviour is great and hard to parallel in other language / compiler environments.