How to make something variable something constant? - flutter

I have a variable list in flutter that won't change anymore once called. The question is: can I make this list constant?
Here is the code:
final number = new List<int>.generate(300, (i) => i + 1);
var rng = new Random();
final place = new List.generate(300, (_) => rng.nextInt(3));
final noteListStart = new List<Note>.generate(number.length, (i) => Note(number[i],place[i]));
final List<Note> noteListEnd = [
Note(300, -1), Note(301, -1),Note(302, -1),Note(303, -1)
];
final initList = List<Note>.from(noteListStart)..addAll(noteListEnd);
List<Note> initNotes1() {
return
initList;
}
In the example above, initNotes1() needs to be constant after being called so I can use it easely somewhere else in the code.
Any help would be appreciated.

At this point, it is unclear what your actual question is.
Taken at face value, you are asking how you can compute a list at runtime and then, once the list is populated, convert it into a constant. Well the answer is this: you can't.
Constants are explicit values that are defined before the program has even compiled. By definition, you cannot create a constant from a computed or generated value (unless it is evaluated from simple expressions involving other values are themselves constant). This means you can't create a constant list full of random values - it is antithetical to the whole concent of what a "constant" is.
(Note: This explanation is a bit specific to Dart, but it is also common among compiled languages. This is different to the definition of a "constant" for an interpreted language such as Javascript, which uses the const keyword to merely refer to an immutable variable.)
If you didn't mean "constant" and merely meant "immutable", then you would mark your list as final which would achieve the same thing. As an extra added measure, you can create the list using List.unmodifiable to make it so its elements couldn't be changed either.
final rng = Random();
final _noteListStart = List.generate(startLength, (i) => Note(i + 1, rng.nextInt(3)));
final _noteListEnd = [
Note(300, -1), Note(301, -1),Note(302, -1),Note(303, -1)
];
List<Note> noteList = List.unmodifiable([..._noteListStart, ..._noteListEnd]);
However, what it appears you are asking is not how to make a variable constant, but instead how to make a variable global. This is a question that is both easier and harder to answer.
It's easier because doing so is quite simple. Take the above code, rearrange it a bit, and put it into its own dart file which you can then import and use wherever you wanted:
// notes_list.dart
final _noteListEnd = [
Note(300, -1), Note(301, -1),Note(302, -1),Note(303, -1)
];
List<Note> _initList(int startLength) {
final rng = Random();
final _noteListStart = List.generate(startLength, (i) => Note(i + 1, rng.nextInt(3)));
return List.unmodifiable([..._noteListStart, ..._noteListEnd]);
}
final List<Note> noteList = _initList(300);
// other_file.dart
import '/path/to/notes_list.dart';
void main() {
print(noteList);
}
(Note: The import is mandatory - you cannot make anything _truly_ global in Dart and eliminate the need to import it.)
On the flip side, this question is harder to answer because the practice of making global variables is frowned upon by many programmers. It belongs to a class of practices that leads to tightly coupled and difficult-to-test code which in turn results in programs that are near impossible to maintain and evolve. In many cases, global variables can be replaced entirely by another practice, such as dependency injection.

Related

Dynamic Type Casting in Dart/Flutter

I am in the middle of writing a library to dynamically serialise/deserialise any object in Dart/Flutter (Similar in idea to Pydantic for Python). However, I am finding it impossible to implement the last component, dynamic type casting. This is required in order convert types from JSON, such as List to List (or similar). The types are retrieved from objects using reflection.
The below is the desired implementation (though as far as I understand this is not possible in Dart).
Map<String, Type> dynamicTypes = {"key": int };
// Regular casting would be "1" as int
int value = "1" as dynamicTypes["key"];
Is there some workaround which makes this possible to implement? Or have I reached a dead end with this (hence no other dynamic serialisation/deserialisation package already exists).
Conducting more research into this issue, it seems in Dart's current implementation this is impossible due to runtime reflection being disabled as referenced here in the official docs.
There are ongoing discussions about the support for this and the associated package dart:mirrors here on GitHub, but so far though there is some desire for such functionality it is highly unlikely to ever be implemented.
As a result, the only options are:
Use code generation libraries to generate methods.
Manual serialisation/deserialisation methods.
Implement classes with complex types such as lists and maps to be dynamic, enabling (all be it limited) automatic serialisation/deserialisation.
Your question does not specify how exactly dynamicTypes is built, or how its key is derived. So there is perhaps a detail to this that is not clear to me.
But what about something like this?
class Caster<T> {
final T Function(String) fromString;
Caster(this.fromString);
}
void main() {
Map<String, Caster> dynamicTypes = { "key": Caster<int>((s) => int.parse(s)) };
int v = dynamicTypes['key']!.fromString('1');
print(v);
}
Or, if you have the value as a dynamic rather than a string:
class Caster<T> {
T cast(dynamic value) => value as T;
}
void main() {
Map<String, Caster> dynamicTypes = { "key": Caster<int>() };
dynamic a = 1;
int v = dynamicTypes['key']!.cast(a);
print(v);
}
Or even more succinctly:
void main() {
dynamic a = 1;
int v = a;
print(v);
}

Dart assert not working when use List.length

I want to check List length when initialize class.
I tried but it did not work as expected.
My code is here.
#immutable
class TestClass {
const TestClass(this.values)
: assert(values.length >= 0 && values.length <= 4);
final List<int> values;
}
const a = TestClass(<int>[1, 1, 1]); // assert
How can I get it to behave as expected?
Edit 1
Now the assertion no longer works.
Edit 2
Edit 3
// OK
final ok = TestClass(const <int>[1]);
// NG
final ng = TestClass(const <int>[1, 1, 1, 1, 1]);
Edit 4
#immutable
class TestClass2 {
const TestClass2(
this.value,
) : assert(value.length == 3);
final String value;
}
final a = TestClass2('abcde');
I think T.length doesn't work in assert.
Edit 5
Edit 6
I don't have enough reputation to add a comment, so I'll add it as an answer.
Apparently, this is working as expected. Found this issue on the Dart SDK repository which is similar. In a comment someone referenced the following from the language specification:
You cannot get the length of a list in a constant expression. The language specification says so here:
\item An expression of the form \code{$e$.length} is potentially constant
if $e$ is a potentially constant expression.
It is further constant if $e$ is a constant expression that
evaluates to an instance of \code{String}.
So it must be rejected at compile-time. This is one of many situations where it's tempting to make Dart constant expressions just a little bit more expressive, but it is quite costly (in so many ways) so it's not very likely to happen. One issue is that you can write a class MyList extends List<String> {...} and make the length getter run arbitrary code, and still have a const constructor in MyList, and constant expressions will not run arbitrary code, so you'd need to find the right borderline between the lists where .length is OK and the lists where it isn't, and the type system wouldn't be able to prevent the latter from occurring where a List or List<T> for some T is specified.
Not sure if there's a way around this, but I hope this helps a bit.
#immutable
class TestClass {
const TestClass(this.values) : assert(values.length == 0 || values.length > 4);
final List<int> values;
}
I edited my answer you will get a warning if values ​​variable has no elements or has more than 4 elements

How to perform deep copy for a list to another list without affecting the original one in Flutter

I have two lists of Type object, _types and _filteredTypes:
List<Type> _types = []; // Original list
List<Type> _filteredTypes = []; // Where i bind filter the contents
a Type object is:
class Type extends Equatable {
final int id;
final String title;
List<SubType>? subTypes;
Type({
required this.id,
required this.title,
this.subTypes,
});
}
a SubType object is:
class SubType extends Equatable {
final int id;
final String title;
Type({
required this.id,
required this.title,
});
}
I need to filter the list based on search text, so whenever user types a letter the _filteredTypes being updated.
I do the filter on _onSearchChangedEvent() within setState() like this:
_filteredTypes = List.from(_types); // To get the original list without filter
for(var i = 0; i < _filteredTypes.length; i++) {
// This is where i filter the search result when a subType.title matches the search query:
_filteredTypes[i].subTypes = List.from(_types[i].subTypes!.where((element) => element.title.toLowerCase().contains(query!.toLowerCase())).toList());
}
// This is where i filter the search result and remove any type doesn't match any subType.title:
_filteredTypes.removeWhere((element) => element.subTypes!.length == 0);
bindTypes(); // To refresh the list widget
The problem is when i need get the original list i get the main type but type.subTypes is still filtered based on the previous search not the original one! even it is copied without reference _filteredTypes = List.from(_types);
It seems like a bug in Flutter, any idea guys?
List.from does not provide you with a deep copy of _types- it gives you a shallow copy. Meaning both _filteredTypes and _types share the same subTypes. It's similar in that behavior to this example
var sharedList = [1];
final listOne = [1, sharedList];
final listTwo = [1, sharedList];
sharedList[0] = 2;
Changing sharedList will change the value in both listOne and listTwo. If shared list was just an integer, changing that integer would not produce the same effect. Like in this example:
var sharedInteger = 1;
final listOne = [1, sharedInteger];
final listTwo = [1, sharedInteger];
sharedInteger = 2;
When you create an instance of a class may it be built in like List or your own custom class, what you get returned is a reference or a pointer to that instance/object. The object itself is allocated on the heap memory area rather than on the stack which means that this object can be referenced outside of functions. As in its life (object life) is not bound by the scope of the function so when you reach the end } of the function the object still exists, and its memory is freed by a special program called the garbage collector.
In dart as in many modern programming languages garbage collectors are used and objects are automatically allocated on the heap. In languages such as C++ for example you can allocate objects on the stack, and you have to be explicit about heap allocation, and deallocate any objects on the heap when you are done with them.
All of the above you can look up the gist of it is since subtypes is a list, it's a reference type so both _filteredTypes and _types have that reference. If you want a deep copy you can do that as well, and I'll leave it for you to look that up.
This is how to perform a deep copy for a list has sub-list, thanks moneer alhashim, your answer guided me.
I'm posting it as an answer to help someone else find the solution easy.
So, the key here is to map the original list types.map(...) and fill it manually instead of using List.from(), and that will create a new instance for deep objects.
First, i declared one function for each list:
//For the parent list:
List<Types> getNewTypesInstance {
// This function allows to perform a deep copy for the list.
return types.map((e) =>
Type(id: e.id, title: e.title, subTypes: e.subTypes))
.toList();
}
// For the child list:
List<SubType> getNewSubTypesInstance(List<SubType> lst) {
// This function allows to perform a deep copy for the list:
return lst.map((e) =>
SubType(id: e.id, title: e.title))
.toList();
}
And if you have more deep list(s), you will need third function to obtain it as new instance and so on.
Finally, the way how to call them is to write this code within setState():
_filteredTypes = getNewTypesInstance
for(var i = 0; i < _filteredTypes.length; i++) {
// This is where i filter the search result when a subType.title matches the search query:
_filteredTypes[i].subTypes = List.from(getNewSubTypesInstance(_types[i].subTypes!.where((element) => element.title.toLowerCase().contains(query!.toLowerCase())).toList()));
}
// This is where i filter the search result and remove any type doesn't match any subType.title:
_filteredTypes.removeWhere((element) => element.subTypes!.length == 0);
bindTypes(); // To refresh the list widget

Is there no simple way to make a deep of lists in flutter?

I tried List.from and [...orginalObject], but neither does a deep copy. In both cases it's clearly just copying the references. Which means if I change any data in the list in which I copied the data, the original data gets changed too.
It seems to me that the only way to do a for loop and define each of the entries the copied list with a new operator and the data from each of corresponding entries from the original list. Something as shown in the following image.
Seems like quite a tedious approach. Is there any simpler approach?
Thanks.
In vanilla Dart, not really, since this would require the ability to copy the leaf objects, and there is no way for the language to know how to do that for arbitrary objects.
However, the built_value and built_collection packages may solve your issue. One of their main features is deep immutability. First, you write your classes like this:
class Item {
final String foo;
final int bar;
Item(this.foo, this.bar);
}
// becomes
part 'item.g.dart';
abstract class Item extends Built<Item, ItemBuilder> {
Item._();
factory Item([void Function(ItemBuilder) updates]) = _$Item;
// boilerplate, can use tooling to auto-generate
String get foo;
int get bar;
}
This lets you create an immutable object using a mutable Builder and then finalizing it, e.g.:
final item1 = Item((b) {
// here b is an ItemBuilder, the mutable version of Item
b.foo = 'Hello';
b.bar = 123;
});
final item2 = item1.rebuild((b) => b.foo = 'New Value'); // Item(foo: 'New Value', bar: 123)
You can then use built_collection to work with deeply immuatble collections of built values, e.g.:
final list = BuiltList<Item>([item1, item2, item3]);
final deepCopy = list.rebuild((b) {}); // rebuild with no changes
final withNewElement = list.rebuild((b) => b.add(item4));
The important thing with all of these is that they are all immutable, and are "value objects", meaning (among other things) that they are considered equal if all their corresponding values are equal. You can consider each rebuild call to be returning you a brand new list with all the values copied over.
In fact, the library is smart enough to only create new objects for values that have actually changed, but because it is immutable, it acts like a deep copy, without the potential performance costs.
The main downside with these libraries is that they rely on code generation, so it requires a bit more setup than just putting it in your dependencies. In return, you get a lot of useful features in addition to having deeply immutable objects (like json serialization, null checking in pre-null-safety code, #memoized to cache results of expensive computations`, etc)
Dart does not have copy constructors nor have required clone() methods on objects, so there is no way to copy an arbitrary object, and therefore there is no way to make a deep copy of a collection of arbitrary objects.
cameron1024's answer suggesting the use of package:built_value and package:built_collection is good. If they're not suitable for you, however, you could make a function that copies elements via a callback:
List<T> copyList<T>(Iterable<T> items, T Function(T element) copier) {
return [
for (var item in items) copier(item),
];
}
class Foo {
int i;
String s;
Foo(this.i, this.s);
#override
String toString() => 'Foo($i, "$s")';
}
void main() {
var list = [Foo(1, 'one'), Foo(2, 'two'), Foo(3, 'three')];
print('Original: $list');
var copy = copyList<Foo>(list, (foo) => Foo(foo.i, foo.s));
list[0].i = 100;
print('Mutated: $list');
print('Copy: $copy');
}

Different ways to define lists and maps (Dart/Flutter)

Dart allows you to write either pattern A or pattern B below, which is the most common way to write it?
Also, how should I use patterns A and B differently?
// Pattern-A
List<String> list = [];
Map<String, String> map = {};
// Pattern-B
var list = <String>[];
var map = <String, String>{};
The official recommendation, as per Effective Dart, is to use var/final for local initialized variables
AVOID type annotating initialized local variables.
Linter rule: omit_local_variable_types
Local variables, especially in modern code where functions tend to be small, have very little scope. Omitting the type focuses the reader’s attention on the more important name of the variable and its initialized value.
DO:
List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
var desserts = <List<Ingredient>>[];
...
return desserts;
}
AVOID:
List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
List<Ingredient> desserts = <List<Ingredient>>[];
...
return desserts;
}