How to convert List<int> to List<Float> with Flutter? - flutter

I have a function that returns List But in my case I want to read and display float values. However, this function is a system function I can't update it.
My question is how to convert List to List?
This is the code:
characteristic.value.listen((event) async {
var bleData = SetupModeResponse(data: event);
});
Event is by default a List. When I try to declare data as List; I got List cannot assigned to List.
I would be very thankful if you can help me.

you can use the map method on list
like that:
List<int> intList = [1, 2, 3];
List<double> doubleList = intList.map((i) => i.toDouble()).toList();
You can learn more about dart list mapping here map method

This should also work:
List<int> ints = [1,2,3];
List<double> doubles = List.from(ints);

Yo can try this method and see if it works
List<int> num = [1,2,3];
List<double> doubles = List.from(num);

Try the following code:
List<double> doubleList = event.map((i) => i.toDouble()).toList()

Related

How do I create a Map of int and list?

I feel like I missed something, as this question seems so easy to answer. However, I haven't found anything on stack overflow or in the dart docs.
What I've tried:
var list = Map<int, List<int>>();
list[0] = [];
or
var list = Map<int, List<int>>();
list[0] = List<int> listOne;
The docs didn't help much:
https://dart.dev/guides/language/language-tour#maps
And a similar question doesn't seem to exist.
How can I solve this problem. Do I need to use a workaround?
Greetings.
Map of int and list
var listMapping = Map<int, List<int>>();
listMapping[0] = [];
listMapping[33] = [12, 0, 345, -23, 999999];
listMapping[45] = List<int>();
listMapping[45].add(101);
listMapping[45].add(109);
print(listMapping[33]);
// A map doesn't store things in a asequencial data structure e.g. List or array
// Hence it doesn't implement Iterable and hence it can not be traversed like below
/*for(List<int> list in listMapping){
print(list);
}*/
List of List
If the integer key in your case is just to store the index and will always be sequencial e.g. 0,1,2,3... then a better solution would be a List of a Lists
var myLists = List<List<int>>()
myLists.add([1,2,45,56,78]);
var aNewList = [22,33,44,55];
myLists.add(aNewList);
The first one looked fine
Im not sure if I am understanding you correctly, but your first attempt worked for me in the DartPad. I only renamed it to map, as it is a map which contains lists.
var map = Map<int, List<int>>();
map[0] = [];
You could also declare it as a final, as the variable itself doesn't get reassigned
final map = Map<int, List<int>>();
map[0] = [];
Give it a type annotation, if it helps you
final Map<int,List<int>> map = Map<int, List<int>>();
map[0] = [];
The second code snippet does not work
var list = Map<int, List<int>>();
//you cannot name a value you want to assign
list[0] = List<int> listOne;
Maybe this is what you were going for:
var list = Map<int, List<int>>();
final listOne = <int>[];
list[0] = listOne
Map literals
This is the way I would do it
final map = {0: []};
//or for added clarity
final Map<int,List<int>> map = <int,List<int>>{0: []};
Simple operations with the map and its keys (int) and values (List)
//assign new array to different keys
map[0] = [0,1,2,3,4];
map[2] = <int>[];
map[4] = <int>[0,3];
//remove all values with an array length smaller than two
map.removeWhere((key,value)=>value.length<2);
//remove value at key 0
map.remove(0);
//clear map
map.clear();
[NOTE] If you want to reassign a completely new map to map, you would have to declare it non final
Map<int, List<int>> map = Map<int, List<int>> ();
map[0] = [10,0];
map[1] = [];
Learn more about dart maps

Flutter: List is deprecated? [duplicate]

This question already has answers here:
The default 'List' constructor isn't available when null safety is enabled. Try using a list literal, 'List.filled' or 'List.generate'
(4 answers)
Closed 1 year ago.
After upgrading to the latest version of flutter, I get a deprecation warning for all my Lists.
List<MyClass> _files = List<MyClass>();
=>'List' is deprecated and shouldn't be used.
Unfortunately, it does not give a hint of what to replace it with.
So what are we supposed to use instead now?
Dart SDK version: 2.12.0-141.0.dev
Flutter: Channel master, 1.25.0-9.0.pre.42
Ok, found it, it's just how to instantiate it:
List<MyClass> _files = [];
Edit: maybe the most common ones, a bit more detailed according to the docs:
Fixed-length list of size 0:
List<MyClass> _list = List<MyClass>.empty();
Growable list:
List<MyClass> _list = [];
//or
List<MyClass> _list = List<MyClass>.empty(growable: true);
Fixed length with predefined fill:
int length = 3;
String fill = "test";
List<String> _list = List<String>.filled(length, fill, growable: true);
// => ["test", "test", "test"]
List with generate function:
int length = 3;
MyClass myFun(int idx) => MyClass(id: idx);
List<MyClass> _list = List.generate(length, myFun, growable: true);
// => [Instance of 'MyClass', Instance of 'MyClass', Instance of 'MyClass']
List<MyClass> myList = <MyClass>[];
From:
_todoList = new List();
Change to:
_todoList = [];
old version
List<Widget> widgetList = new List<Widget>();
new version
List<Widget> widgetList = [];

Extract number and separate with comma from list in Flutter

List listFinal = [];
So listFinal have values from multiple list inside like below.
[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]]
How do I make this list so that it only extract numbers and separate with comma?
End result should be like
[1113335555, 2223334555, 5553332222]
I can think of trimming or regexp but not sure how to pull this off.
many thanks.
Try this
void main() {
List<String> numberList=[];
List<List<dynamic>> demoList=[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]];
for(int i=0;i<demoList.length;i++){
numberList.addAll(demoList[i].map((e) => e.toString().split(":")[1].replaceAll("-", "")).toList());
}
print(numberList.toString());
}
Here is an example to get you started. This doesn't handle things like malformed input strings. First step is to "flatten" the list with .expand, and then for each element of the flattened iterable use a regex to extract the substring. Other options might include using .substring to extract exactly the last 12 characters of the String.
You can see this in action on dartpad.
void main() {
final input = [
['test: 111-333-5555', 'test2: 222-333-4555'],
['test3: 555-333-2222']
];
final flattened = input.expand((e) => e); // un-nest the lists
// call extractNumber on each element of the flattened iterable,
// then collect to a list
final result = flattened.map(extractNumber).toList();
print(result);
}
final _numberRegExp = RegExp(r'.*: ([\d-]+)$');
int extractNumber(String description) {
var numberString = _numberRegExp.firstMatch(description).group(1);
return int.parse(numberString.replaceAll('-', ''));
}
Let's do this in a simple way.
List<List<String>> inputList = [
["test: 111-333-5555", "test2: 222-333-4555"],
["test3: 555-333-2222"]
];
List resultList = [];
print('Input List : $inputList');
inputList.forEach((subList){
subList.forEach((element){
var temp = element.split(' ')[1].replaceAll('-', '');
resultList.add(temp);
});
});
print('Output List : $resultList');
Here I have taken your list as inputList and stored the result in resultList.
For each element of inputList we get a sub-list. I have converted the elements of that sub-list into the needed format and added those into a List.
Happy Coding :)

Is there any way to find unique values between two lists without using a loop in dart

Is there any way to find unique values between two lists without using a loop?
List<String> first = ['A','B','C','D'];
List<String> second = ['B','D'];
I need the result to be like this:
result = ['A','C'];
You can use where() with contains() methods from List:
void main() {
List<String> first = ['A','B','C','D'];
List<String> second = ['B','D'];
List<String> result = first.where((item) => !second.contains(item)).toList();
print(result); // [A, C]
}
Edit in DartPad.

What is wrong with the below lambda expression for multiplication(C#3.0)

List<double> y = new List<double> { 0.4807, -3.7070, -4.5582,
-11.2126, -0.7733, 3.7269,
2.7672, 8.3333, 4.7023 };
List<double> d1 = y.ForEach(i => i * 2);
Error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
What is wrong?
Thanks
List<T>.ForEach doesn't perform a conversion: it executes the given delegate for each item, but that's all. That's why it has a void return type - and why the parameter type is Action<T> rather than something like Func<T, TResult>. This last part is why you've got a compilation error. You're basically trying to do:
Action<double> = i => i * 2;
That will give you the same compilation error.
If you want to stick within the List<T> methods (e.g. because you're using .NET 2.0) you can use List<T>.ConvertAll:
List<double> d1 = y.ConvertAll(i => i * 2);
Try instead:
List<double> d1 = y.Select(i => i * 2).ToList();
List.Foreach takes an Action<> delegate which does not return anything, so you cannot use it to create a new list that way. As others have pointed out, using ForEach is not the best option here. A sample on how to perform the operation using ForEach might help to understand why:
List<double> y = new List<double> { 0.4807, -3.7070, -4.5582,
-11.2126, -0.7733, 3.7269,
2.7672, 8.3333, 4.7023 };
List<double> d1 = new List<double>();
Action<double> a = i => d1.Add(i*2);
y.ForEach(a);
List<double> d1 = y.ForEach(i => i = i * 2);