dart how to assign list into a new list variable - dart

I am trying to extend a list just by using add method like this
List<String> mylists = ['a', 'b', 'c'];
var d = mylists.add('d');
print(d);
It gives error
This expression has type 'void' and can't be used.
print(d);
Why i cannot save the list in a new variable? Thank you

mylists.add('d') will add the argument to the original list.
If you want to create a new list you have several possibilities:
List<String> mylists = ['a', 'b', 'c'];
// with the constructor
var l1 = List.from(mylists);
l1.add('d');
// with .toList()
var l2 = mylists.toList();
l2.add('d');
// with cascade as one liner
var l3 = List.from(mylists)..add('d');
var l4 = mylists.toList()..add('d');
// in a upcoming version of dart with spread (not yet available)
var l5 = [...myList, 'd'];

Refering Dart docs: https://api.dartlang.org/stable/2.2.0/dart-core/List-class.html
The add method of List class has return type of void.
So you were unable to assign var d.
To save list in new variable use:
List<String> mylists = ['a', 'b', 'c'];
mylists.add('d');
var d = mylists;
print(d);
First add the new String i.e. 'd'
And then assign it to new variable

Related

Assign const list variable to a non const list variable and modify it

I have created a constant list variable and I want to put it to a new list variable and modify its items. But I get an error Unhandled Exception: Unsupported operation: Cannot remove from an unmodifiable list
const List<String> constantList = [
'apple',
'orange',
'banana'
];
List<String> newList = [];
newList= constantList;
newList.remove('banana');
The const'nes of an object is on the object and not the variable. So even if you change the type of the variable, the object is still going to be const.
One problem in your example:
List<String> newList = [];
newList= constantList;
This is not doing what you think it does. What it actually does is it creates a new empty list, and assings newList to point to this new list.
You are then changing newList to point at the list instance pointed at by constantList. So after this code is done, newList and constantList points to the same constant list object.
If you want to make a copy of the list refer to by constantList, you can do this:
void main() {
const List<String> constantList = ['apple', 'orange', 'banana'];
List<String> newList = constantList.toList();
// Alternative: List<String> newList = [...constantList];
newList.remove('banana');
print(newList); // [apple, orange]
}
Also, you can try with .addAll()
void main(List<String> args) {
const List<String> constantList = ['apple', 'orange', 'banana'];
List<String> newList = [];
newList.addAll(constantList);
newList.remove('banana');
print(newList); //[apple, orange]
}
This copy is not a const list and can therefore be manipulated.
More about pass-by-reference

How to Split List in Flutter

I have a list1: var list1 = ["a:1", "b:2", "c:3"];
how can I create list2 based on list1 like this: ["a", "b", "c"]
I thought I would have to use split and forEach but I don't know how to combine it
Maybe this works for you, if and only if you always have the same String length
List<String> list1 = ["a:1", "b:2", "c:3"];
List<String> list2 = list1.map((f) => f.substring(0,1)).toList();
Or if you wanted to have ":" as the basis regardless of the String length for each element then you can try the code below
List<String> list1 = ["a:1", "b:2", "c:3"];
List<String> list2 = list1.map((f) => f.split(":")[0]).toList();
Iterate through all items of the list with forEach.
With every item (which is a string), split it using ':' as separator (or, if its always just one character, simply get the first charaxter of the item.
Add the first element of the result of split (or aimply first charaxter of item) to list2.
var list1 = ["a:1", "b:2", "c:3"];
List list2;
list1.asMap().forEach((key, value) {
list2.add(value.replaceAll(':${key + 1}', ''));
});
Here is my code

how to filter a list with condition in dart

I have a list and I want to put a condition on it. for example, I want to have items from list lst that value greater than 10:
var lst = [{"value":5 , "name":"test1"},
{"value":12 , "name":"test2"},
{"value":8 , "name":"test3"},
{"value":23 , "name":"test4"}];
/*
output: value greater than 10 =>
[{"value":12 , "name":"test2"},
{"value":23 , "name":"test4"}]
*/
You can either use the where function on iterables to filter its elements, then convert the resulting iterable back to a list, or use the list literal syntax, or a combination of the two where you "spread" the result of where:
var list = [ ... ];
var filtered1 = list.where((e) => e["value"] > 10).toList();
var filtered2 = [for (var e in list) if (e["value"] > 10) e];
var filtered3 = [... list.where((e) => e["value"] > 10)];
To filter a list base on a condition you can use List.where which takes a test function and returns a new Iterable that contains the elements that match the test.
To get a list with only the values greater than 10 you can filter you list of maps as such:
lst.where((e) => e['value'] > 10); //Returns a lazy Iterable
if you need to modify your list later you can append a .toList(), to get a new list.
try to use this code:
List lst = [{"value":5 , "name":"test1"} ,{"value":12 , "name":"test2"} , {"value":8 , "name":"test3"} , {"value":23 , "name":"test4"} ];
List newLst = lst.where( (o) => o['value'] > 5).toList();
print(newLst);
> Just try this Function, catogory_id == 1 is condition here
List<dynamic> chooseCatogory(List<dynamic> list) {
List newlist = list.where((o) => o['category_id'] == '1').toList();
return newlist;
}

Create class instance from string in dartlang

I have created this class
class Opacity {
String a,b,c;
Opacity({this.a, this.b,this.c});
}
And I'm trying to dynamically create an instance of this class only using strings and an hashmap for arguments.
String type = "Opacity";
List<String> args = {'a': 'a', 'b': 'b','c': 'c'}
And I have one constraint, I can't modify the Opacity class.
For creating the instance I thought about using reflection to dynamically create the class from string but I can't figure out how to pass the arguments dynamically.
For passing arguments dynamically to the constructor you can use newInstance method of ClassMirror.
For example
MirrorSystem mirrors = currentMirrorSystem();
ClassMirror classMirror = mirrors.findLibrary(Symbol.empty).declarations[new Symbol('Opacity')];
print(classMirror);
var arguments = {'a': 'a', 'b': 'b', 'c': 'c'}.map((key, value) {
return MapEntry(Symbol(key), value);
});
var op = classMirror.newInstance(Symbol.empty, [], arguments);
Opacity opacity = op.reflectee;
print("opacity.a: ${opacity.a}");
print("opacity.b: ${opacity.b}");
print("opacity.c: ${opacity.c}");
Going from a string to a source name, and further to the thing denoted by that source name, is reflection. It's only available through the dart:mirrors library, or if you generate code ahead-of-time, perhaps using package:reflectable.
This is a point where Dart differs from a language like JavaScript, where you can inspect all values at run-time.
Without reflection, the only way you can call a constructor is if you have actual code performing that call in your code. That would mean that you have to have code like Opacity(a: ..., b: ..., c: ...) at least in one place in your code.
You could define a function like:
Opacity createOpacity(Map<String, String> args) =>
Opacity(a: args["a"], b: args["b"], c: args["c"]);
Then you could perhaps register it by name as:
Map<String, Function> factories = {"Opacity": createOpacity};
and finally use it as:
var type = "Opacity";
var args = {'a': 'a', 'b': 'b', 'c': 'c'};
Opacity myOpacity = factories[type](args);

Using DataBinder for casting the whole object in one step

Is it possible to cast the whole object using DataBinder.Eval() instead of casting it by property. e.g.:
// instead of this
var p = new Person();
p.FirstName = Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "FirstName"));
p.Age = Convert.ToInt32(DataBinder.Eval(Container.DataItem, "Age"));
...
// use something like this in one step
var p = DataBinder.Eval<Person>(Container.DataItem);

Resources