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
Related
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()
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 = [];
I'm looking every where on the web (dart website, stackoverflow, forums, etc), and I can't find my answer.
So there is my problem: I need to write a function, that print a random sort of a list, witch is provided as an argument. : In dart as well.
I try with maps, with Sets, with list ... I try the method with assert, with sort, I look at random method with Math on dart librabry ... nothing can do what I wana do.
Can some one help me with this?
Here some draft:
var element03 = query('#exercice03');
var uneliste03 = {'01':'Jean', '02':'Maximilien', '03':'Brigitte', '04':'Sonia', '05':'Jean-Pierre', '06':'Sandra'};
var alluneliste03 = new Map.from(uneliste03);
assert(uneliste03 != alluneliste03);
print(alluneliste03);
var ingredients = new Set();
ingredients.addAll(['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']);
var alluneliste03 = new Map.from(ingredients);
assert(ingredients != alluneliste03);
//assert(ingredients.length == 4);
print(ingredients);
var fruits = <String>['bananas', 'apples', 'oranges'];
fruits.sort();
print(fruits);
There is a shuffle method in the List class. The methods shuffles the list in place. You can call it without an argument or provide a random number generator instance:
var list = ['a', 'b', 'c', 'd'];
list.shuffle();
print('$list');
The collection package comes with a shuffle function/extension that also supports specifying a sub range to shuffle:
void shuffle (
List list,
[int start = 0,
int end]
)
Here is a basic shuffle function. Note that the resulting shuffle is not cryptographically strong. It uses Dart's Random class, which produces pseudorandom data not suitable for cryptographic use.
import 'dart:math';
List shuffle(List items) {
var random = new Random();
// Go through all elements.
for (var i = items.length - 1; i > 0; i--) {
// Pick a pseudorandom number according to the list length
var n = random.nextInt(i + 1);
var temp = items[i];
items[i] = items[n];
items[n] = temp;
}
return items;
}
main() {
var items = ['foo', 'bar', 'baz', 'qux'];
print(shuffle(items));
}
You can use shuffle() with 2 dots like Vinoth Vino said.
List cities = ["Ankara","London","Paris"];
List mixed = cities..shuffle();
print(mixed);
// [London, Paris, Ankara]
I'm trying to assign a Map<string, string> argument to double. If that's even what I have to do. I have no idea how to work with this argument type. Here it is:
await sheet.values.map.column(3)
I'm using this to extract column #3 and all its values from a google sheet via gsheets. This is a nightmare to work with... Anybody know if there's another way to call the column? or if there's a way to convert the Map<string, string> to a single string containing only the values in the column ? In this case, they're coordinate values for longitude or latitude. I'm trying to call these values for plotting in Google maps. Here's the rest of my code:
Iterable markers = [];
var latstr = (sheet.values.map.column(3)); //latitude
var lngstr = (sheet.values.map.column(4)); //longitude
List<dynamic> names = [];
List<double> lat = [];
List<double> lng = [];
for (var i = 0; i < 10; i++) {
names.add(latstr);
lat.add(parse(await sheet.values.map.column(3)); //<--- I have no idea what I'm doing here. Trying to convert to double. very confused.
lng.add(await sheet.values.map.column(4));
}
to add to this, here's the full error:
The argument type 'Map<String, String>' can't be assigned to the
parameter type'double'.
here's how i'm pulling from google sheets:
const _spreadsheetId = 'xxxxxxxxxxxxxx';
final gsheets = GSheets(_credentials);
final ss = await gsheets.spreadsheet(_spreadsheetId);
var sheet = await ss.worksheetByTitle('xxxxxxxxxxxx');
As the document says await sheet.values.map.column(4) gives you a Map<String,String>, but lng is List<double>, so only doubles can be added to it but you are trying to asign a Map<String,String> which results in the error,
//try this to map the map into a map of doubles (mapception), if your okey with using Map instead of a list
Map<double,double> m = (await sheet.values.map.column(4)).map((key, value)=> MapEntry(double.parse(key), double.parse(value)));
parse will throw if it encounters a character which is not a digit
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.