How to Split List in Flutter - dart

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

Related

Fetch random items from list without duplicate or repetition - Dart

I'm trying to fetch the randomly specific number of items from one list and add them to the other list but without duplication.
For example: pick three random items from the list randomly and put them into another list. This is what I have achieved so far but this could pick the duplicate item again.
List itemList = ['NAME1', 'NAME2', 'NAME3', 'NAME4', 'NAME3', 'NAME5', 'NAME2'];
List randomItems = [];
for(var i=0; i<=2; i++){ // run the loop for three times
int randomNumber = Random().nextInt(itemList.length); //generate random number within itemList range
randomItems.add(itemList[randomNumber]); // duplication occur, for example: NAME2 could be added two times
}
There are several steps we can do to solve this problem. First, we want to get rid of the duplicate elements in the list. We can here do that by converting the list to a Set:
List<String> itemList = [
'NAME1',
'NAME2',
'NAME3',
'NAME4',
'NAME3',
'NAME5',
'NAME2'
];
Set<String> itemSet = itemList.toSet();
print(itemSet); // {NAME1, NAME2, NAME3, NAME4, NAME5}
Then, we want to extract 3 random elements from this new Set in such a way that we can't select the same element twice. The easiest way to solve this is by shuffle the elements randomly and then take elements from our collection. But Set does not have the concept of any specific "order" and we can't therefore shuffle our Set.
So let's convert our Set back to a List:
Set<String> itemSet = itemList.toSet();
List<String> itemListFromSet = itemSet.toList();
print(itemListFromSet); // [NAME1, NAME2, NAME3, NAME4, NAME5]
We can then shuffle this new list:
itemListFromSet.shuffle();
print(itemListFromSet); // [NAME3, NAME2, NAME4, NAME5, NAME1]
If we then want 3 random selected elements, we can just take 3 elements from this randomly ordered list. So e.g. (take returns an iterable which we then makes a new list of):
List<String> randomItems = itemListFromSet.take(3).toList();
A complete solution would look like:
void main() {
List<String> itemList = [
'NAME1',
'NAME2',
'NAME3',
'NAME4',
'NAME3',
'NAME5',
'NAME2'
];
Set<String> itemSet = itemList.toSet();
List<String> itemListFromSet = itemSet.toList();
itemListFromSet.shuffle();
List<String> randomItems = itemListFromSet.take(3).toList();
print(randomItems); // [NAME5, NAME2, NAME4]
}
Which can be reduced down to:
void main() {
List<String> itemList = [
'NAME1',
'NAME2',
'NAME3',
'NAME4',
'NAME3',
'NAME5',
'NAME2'
];
List<String> randomItems =
(itemList.toSet().toList()..shuffle()).take(3).toList();
print(randomItems); // [NAME3, NAME4, NAME2]
}

Stable list set-difference in Dart

We have two lists
List<String> list1 = ['foo', 'bar', 'blah', 'bee', 'fog'];
List<String> list2 = ['bee', 'bar'];
and we'd like to remove from the first the items in the second.
We can iterate, removing those in the second one by one
for (var v in list2) {
list1.removeWhere((item) => item == v);
}
but that's silly. It'll take time proportional to the product of the length of the two lists.
We can convert to sets and use Dart's Set.difference(), then return a list.
n = (n.toSet().difference(m.toSet())).toList();
but we lose the order of the items in list1.
What's a good way for determining stable list set-difference in Dart?
A solution would be to convert list2 into a Set to make it more efficient to ask if an element from list1 is part of list2. We can then use removeWhere to remove elements from list1:
void main() {
List<String> list1 = ['foo', 'bar', 'blah', 'bee', 'fog'];
List<String> list2 = ['bee', 'bar'];
list1.removeWhere(list2.toSet().contains);
print(list1); // [foo, blah, fog]
}

Insert list items at start of of each item in a list of lists

I have two lists that are the same length:
List<List<String>> list1 = [["John","Omar","Jane"],["Rick","Hulie","Frank"],["Pri","Mary","Tim"]]
List<int> list2 = [1,5,9]
I want to add insert the numbers from list2 to the start of the lists in list1 like this..
list3 to look like
[["1","John","Omar","Jane"],["5", "Rick","Hulie","Frank"],["9","Pri","Mary","Tim"]]
You can loop through the list and insert each of the numbers at index 0.
List<List<String>> list1 = [["John","Omar","Jane"],["Rick","Hulie","Frank"], ["Pri","Mary","Tim"]];
List<int> list2 = [1,5,9];
for (int i = 0;i < list1.length;i++) {
list1[i].insert(0,list2[i].toString());
}
// if you want a more dart like the solution then use this.
list1.asMap().forEach((index,value) => value.insert(0,list2[index].toString()));

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;
}

dart how to assign list into a new list variable

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

Resources