Insert element at the beginning of the list in dart - list

I am just creating a simple ToDo App in Flutter. I am managing all the todo tasks on the list. I want to add any new todo tasks at the beginning of the list. I am able to use this workaround kind of thing to achieve that. Is there any better way to do this?
void _addTodoInList(BuildContext context){
String val = _textFieldController.text;
final newTodo = {
"title": val,
"id": Uuid().v4(),
"done": false
};
final copiedTodos = List.from(_todos);
_todos.removeRange(0, _todos.length);
setState(() {
_todos.addAll([newTodo, ...copiedTodos]);
});
Navigator.pop(context);
}

Use insert() method of List to add the item, here the index would be 0 to add it in the beginning. Example:
List<String> list = ["B", "C", "D"];
list.insert(0, "A"); // at index 0 we are adding A
// list now becomes ["A", "B", "C", "D"]

Use
List.insert(index, value);

I would like to add another way to attach element at the start of a list like this
var list=[1,2,3];
var a=0;
list=[a,...list];
print(list);
//prints [0, 1, 2, 3]

Adding a new item to the beginnig and ending of the list:
List<String> myList = ["You", "Can", "Do", "It"];
myList.insert(0, "Sure"); // adding a new item to the beginning
// new list is: ["Sure", "You", "Can", "Do", "It"];
lastItemIndex = myList.length;
myList.insert(lastItemIndex, "Too"); // adding a new item to the ending
// new list is: ["You", "Can", "Do", "It", "Too"];

The other answers are good, but now that Dart has something very similar to Python's list comprehension I'd like to note it.
// Given
List<int> list = [2, 3, 4];
list = [
1,
for (int item in list) item,
];
or
list = [
1,
...list,
];
results in [1, 2, 3, 4]

Better yet and in case you want to add more items :-
List<int> myList = <int>[1, 2, 3, 4, 5];
myList = <int>[-5, -4, -3, -2, -1, ...myList];

For those who are looking for an easy method to add multiple items at the start position you can use this reference:
List<int> _listOne = [4,5,6,7];
List<int> _listTwo = [1,2,3];
_listOne.insertAll(0, _listTwo);

Related

Dart, Flutter: indices of range

How can I get indexes of a range I got by a value not indexes?
For example:
["H", "e", "l", "l", "o"].getRangeIndexes(["e", "l", "l"]);
// [1, 3]
You can write a function like getRangeIndexes as below..
void main() {
List<String> fullStringList = ["H", "e", "l", "l", "o"];
List<String> subStringList = ["e", "l", "l"];
print(getRangeIndexes(fullStringList, subStringList)); //<-- prints [1, 3]
}
List<int> getRangeIndexes(List<String> fullList, List<String> subList){
List<int> rangeIndexes;
String fullString = fullList.join("");
String subString = subList.join("");
if(!fullString.contains(subString)){
rangeIndexes = [-1, -1]; //return [-1, -1] when it does not contain the same sequence
}
else{
int startIndex = fullString.indexOf(subString);
int endIndex = startIndex + (subString.length - 1);
rangeIndexes = [startIndex, endIndex];
}
return rangeIndexes;
}
try
theList.indexOf(subListOfTheList.first);
to get the index of the first element of secondlist in the first list, likewise for the last element in the second list.
theList.indexOf(subListOfTheList.last);
OR
make it a method
///gives you List of indexes of all the items in smalllist as they appear in biglist,respects the order
List<int> giveBackTheIndexes<T>(List<T> main, List<T> sub) {
var biglist = main;
var smalllist = sub;
final indexes = <int>[];
smalllist.forEach((smalllistElement) {
var i = biglist.indexOf(smalllistElement);
indexes.add(i);
if(i!=-1){
biglist[i]=null;
}
});
return indexes;
}
if the value is -1 then item does not exists in the biglist

What is the use of returning [...list] in Dart?

In Dart programming language, sometimes I see functions returning a list in pair of brackets with triple dots [...list]. For example:
class IntList {
List<int> _integerList = [1, 2, 3, 4, 5];
List<int> get integerList {
return [..._integerList];
}
}
So what is the difference between return integerList; and the above return statement?
Any help is really appreciated. Thank you.
For this particular case there is no difference. ... is the spread operator. This allows you to insert multiple elements into a collection.
For example:
var list = [1, 2, 3];
var list2 = [0, ...list];
print(list2)
Output:
[0, 1, 2, 3]
So doing return [..._integerList]; is the exact same as return integerList;, other than that it creates a new list.
var list = [1, 2, 3];
print(list.hashCode);
print([...list].hashCode);
This code shows that they are different List objects when the spread operator is used because of the output of different hash codes.

Kotlin declare list of same values of fixed size

Is it possible to declare a list of same values of fixed size in Kotlin. For example, if the value is 1 and the size is 5. I want to declare a list which would look like below:
[1, 1, 1, 1, 1]
I know I can declare a mutable list, and then populate it with 1's. But is there any shortcut?
Thanks in advance.
easier solution for this, (just as #deHaar answer but immutable one)
List(5) { 1 }
// -> [1, 1, 1, 1, 1]
I think you can just specify the amount of items and the value of each item like this:
fun main(args: Array<String>) {
// specify the list size
val n = 5
// specify the item value
val v = 1
// create a list of size n with v as each value
var myList = MutableList(n) {v}
// print it
println(myList)
}
The output is then
[1, 1, 1, 1, 1]
Using range operator and map function
(1..5).map { 1 })

Is there a Dart utility for converting a flat list into a nested one?

It's a common problem here, but I couldn't find any simplified methods for Dart in particular - how can I convert a list like this
[1, 2, 3, 4, 5, 6]
into a list like this
[[1, 2], [3,4], [5,6]]
assuming there are no extra elements after this?
Dart Quiver package is a set of utility libraries for Dart that makes using many Dart libraries easier and more convenient or adds additional functionality (https://github.com/google/quiver-dart).
You can use the partition function from quiver iterables library as follows.
import 'package:quiver/iterables.dart';
main() {
var list = [1, 2, 3, 4, 5, 6];
# Use partition function to segment lists into chunks of size 2
var newList = partition<int>(list, 2);
print (newList);
}
Result [[1, 2], [3,4], [5,6]]
var list = [1, 2, 3, 4];
List<int> temp = [];
List<List<int>> newList = list.fold<List<List<int>>>([], (newList, i) {
if (temp.length < 2) {
temp.add(i);
}
if (temp.length >= 2) {
List<int> newValue = new List<int>.from(temp);
newList.add(newValue);
temp.clear();
}
return newList;
});
print(newList);

List of List in scala

I would like to know how can I create a List of List in the result of a reduce operation.
I've for example this lines
1,2,3,4
0,7,8,9
1,5,6,7
0,6,5,7
And I would like to get something like this
1, [[2,3,4],[5,6,7]]
0, [[7,8,9],[6,5,7]]
Thsi is my code
val parsedData = data.map { line =>
val parts = line.split(",")
val label = Integer.parseInt(parts(0))
(label, List(Integer.parseInt(parts(1)), Integer.parseInt(parts(2)), Integer.parseInt(parts(3)))
}
With this I get
1, [2,3,4]
0, [7,8,9]
1, [5,6,7]
0, [6,5,7]
But if I use a reduceByKey operation with a List.concat(_,_) I get one single List with all items concated.
parsedData.reduceByKey(List.concat(_,_))
I want a List of List, reduced by the Key.
Is there some other operation that i don't know?
Thanks a lot for your help!
Here is a working example:
val data = "1,2,3,4\n0,7,8,9\n1,5,6,7\n0,6,5,7".split("\n")
val parsedData = data.map{ line =>
val parts = line.split(",")
val label = Integer.parseInt(parts(0))
(label, List(Integer.parseInt(parts(1)), Integer.parseInt(parts(2)), Integer.parseInt(parts(3))))
}.toList
//parsedData: List[(Int, List[Int])] = List((1,List(2, 3, 4)), (0,List(7, 8, 9)), (1,List(5, 6, 7)), (0,List(6, 5, 7)))
parsedData.groupBy(_._1).mapValues(_.map(_._2))
// Map(1 -> List(List(2, 3, 4), List(5, 6, 7)), 0 -> List(List(7, 8, 9), List(6, 5, 7)))
I am not sure this is concat you are looking for.
Can you try with that:
parsedData.reduceByKey(_ :: _ :: Nil)
Which should literally create a new list with your elements inside