How to get Distinct List - flutter

I found online soluton like this:
import 'package:queries/collections.dart';
void main() {
List<String> list = ["a", "a", "b", "c", "b", "d"];
var result = new Collection(list).distinct();
print(result.toList());
}
But, I don't know how to convert var result back to List<Widget>.

There is a way that is a lot easier and does not require any additional imports.
You can convert your List to a Set which inherently only contains distinct elements and then convert that Set back to a List.
If you are using Dart 2.3 or higher (environment: sdk: ">=2.3.0 <3.0.0"), you can use the following idiomatic version:
List<String> list = ['a', 'a', 'b', 'c', 'b', 'd'];
List result = [...{...list}];
The ... spread operator for iterables was just introduced with Dart 2.3.
Otherwise, you can just use old syntax:
List<String> list = ["a", "a", "b", "c", "b", "d"];
List result = list.toSet().toList();

Thank you for your answer,
Here is the full code, i try to modify your method but not working.
(Works only in print)
Future<List<List<Widget>>> getList(List<int> list, String column) async {
List<Widget> list1 = List();
List<Widget> list2 = List();
List<Widget> list3 = List();
//test
List<String> testlista = List();
testlista.add(result[0][column].toString());
List<List<Widget>> listFromDB = [list1, list2, list3];
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'books.db');
Database database = await openDatabase(path, version: 1);
for (int i = 0; i < list.length; i++) {
var result = await database.rawQuery(
'SELECT DISTINCT $column FROM planner WHERE id = ${list[i]}');
//here polulate new List
testlista.add(result[0][column].toString());
if (list[i] < 18) list1.add(_item(result[0][column].toString()));
if (list[i] > 17 && list[i] < 50)
list2.add(_item(result[0][column].toString()));
if (list[i] > 49) list3.add(_item(result[0][column].toString()));
}
//Now this give me corect print list without duplicate!!!
for (int i = 0; i < testlista.length-1; i++) {
print('FROM DELETE method: '+ deleteDuplicate(testlista)[i]);
}
await database.close();
return listFromDB;
}
//Method for removingDuplicate
List<String> deleteDuplicate(List<String> lista) {
// List<String> result = Set.from(lista).toList();
List<String> result = {...lista}.toList();
return result;
}

Related

How can I convert a List<String> to String []?

I have this String
List<String> params = ['A','B','C'];
I want to convert this to "['A']['B']['C']"
How can I convert this properly?
You can try:
void main(){
List<String> params = ['A','B','C'];
final out = params.map((e) => "['$e']").join();
print(out);
}
Prints:
['A']['B']['C']
you can do this
List<String> params = ['A','B','C'];
List newParams = [];
for(var item in params){
newParams.add([item]);
}
String stringParams = newParams.toString();
String noBracketParams = stringParams.substring( 1, stringParams.length - 1 );
String noCommasParams = noBracketParams.replaceAll(',', '');
print(noCommasParams);
I'm not sure what you're trying to do, but it can be achieved like this
List<String> params = ['A', 'B', 'C'];
List.generate(
params.length, (index) => params[index] = '''['${params[index]}']''');
var str = '';
params.forEach((item) => str += item);
print(str);

I am facing struggle to get the result for nested object list to probability tree result form. As Following

Can someone help me for a snip of code.
void main() {
List<List<String>> testList = [["a","b","c"], ["1","2"], ["Y","Z"]];
// Result list I want => a1Y, a1Z, a2Y, a2Z, b1Y, b1Z, b2Y, b2Z, c1Y, c1Z, c2Y, c2Z
}
Similar question Generate all combinations from multiple lists
Answer Source: https://stackoverflow.com/a/17193002/6576315
Dart Version:
void generatePermutations(List<List<String>> lists, List<String> result, int depth, String current) {
if (depth == lists.length) {
result.add(current);
return;
}
for (int i = 0; i < lists.elementAt(depth).length; i++) {
generatePermutations(lists, result, depth + 1, current + lists.elementAt(depth).elementAt(i));
}
}
Usage:
List<List<String>> testList = [["a","b","c"], ["1","2"], ["Y","Z"]];
List<String> result = <String>[];
generatePermutations(testList, result, 0, "");
print(result);
// prints: [a1Y, a1Z, a2Y, a2Z, b1Y, b1Z, b2Y, b2Z, c1Y, c1Z, c2Y, c2Z]
Do upvote the original source if it works

Making a copy/clone of a "List<List<Map>>"

I'm trying to create a copy/clone of a "List<List<Map'>>".
So far I tried:
dataFTY2 = dataFTY.map((element)=>element).toList();
dataFTY2 = json.decode(json.encode(dataFTY));
dataFTY2 = List.from(dataFTY);
Nothing seems to work. Whenever I change the copy "dataFTY2", dataFTY changes as well. I need this to be a completely independent copy. Please help. I cant seem to figure this out, its driving me crazy.
More code added for reference.
List failureDetails = [];
List trackIDs = [];
List dateTime = [];
var dataFTY2 = dataFTY.map((element) => element.map((ele) => Map.from(ele)).toList()).toList();
// get historyData for each one and sort through "F"s and put them into the table in a row?
for (var x in dataFTY2[4]) {
trackIDs.add(x["track_id"]);
dateTime.add(x["datetime"]);
}
List failuresOnly = List.filled(trackIDs.length, {}, growable: true);
for (var i = 0; i < trackIDs.length; i++) {
await fetchTrackIDTestDetails(context, trackIDs[i], dateTime[i], false);
failureDetails.add(MyGlobals().getTestCodeDetailsData());
}
//filter out only "F"s
for (var p = 0; p < failureDetails.length; p++) {
for (var t in failureDetails[p][0]) {
if (t["Status"] == "F") {
//add it to list, if pass do nothing
failuresOnly[p] = t;
}
}
}
//combine with FTY failure data, don't use new screen use old screen and toggle when pressed, add column on right side
//dataFTY2 = MyGlobals().getFTYFailureMoreDetails();
for (var i = 0; i < dataFTY2[4].length; i++) {
dataFTY2[4][i]["TestCode"] = failuresOnly[i]["TestCode"];
dataFTY2[4][i]["Status"] = failuresOnly[i]["Status"];
dataFTY2[4][i]["TestValue"] = failuresOnly[i]["TestValue"];
dataFTY2[4][i]["Lo_Limit"] = failuresOnly[i]["Lo_Limit"];
dataFTY2[4][i]["Up_Limit"] = failuresOnly[i]["Up_Limit"];
dataFTY2[4][i]["ProcTime"] = failuresOnly[i]["ProcTime"];
}
You can use Map.from named constructor to clone the Map like this,
dataFTY2 = dataFTY.map((element) => element.map((ele) => Map.from(ele)).toList()).toList();
I find it more straightforward to use collection-for and the spread (...) operator:
void main() {
var original = [
[
{'foo': 1, 'bar': 2},
{'foo': 3, 'bar': 4},
]
];
// Create a new List...
var copy = [
for (var sublist in original)
// ... where each element is a new List...
[
for (var map in sublist)
// ... where each element of the sublist is a new Map that
// copies all entries from `map`.
{...map},
],
];
original[0][0]['foo'] = -1;
print(original); // Prints: [[{foo: -1, bar: 2}, {foo: 3, bar: 4}]]
print(copy); // Prints: [[{foo: 1, bar: 2}, {foo: 3, bar: 4}]]
}

How to type-cast a dynamic list to a multi-dimensional typed list in dart?

If, I have List<dynamic> dynamicList which is actually List<List<double>> but if I try to cast it using,
dynamicList.cast<List<List<double>>>();
This gives "not a sub-type error",
Therefore to convert it to List<List<double>> I have to,
List<List<double>> converted = [];
for(int i = 0; i < dynamicList.shape[0]; i++){
List<double> subList = [];
for(int j = 0; j < dynamicList.shape[1]; j++){
if(dynamicList[i][j] is double){
subList.add((dynamicList[i][j] as double));
}
}
converted.add(subList);
}
extension Util on List{
List<int> get shape {
if (isEmpty) {
return [];
}
var list = this as dynamic;
var shape = <int>[];
while (list is List) {
shape.add((list as List).length);
list = list.elementAt(0);
}
return shape;
}
}
What could be a better and more generalized way of doing this?
How to cast a List inside a List
which is a dynamic list
List<List<String>> typedList;
typedList = dynamicList.map((value)=>List.cast(value));

Dart-lang, how can I map List<int> to List<String> with combining elements?

I have a list
final List list = [1, 2, 3, 4, 5, 6, 7];
how can I "map" to the output as a new List like:
"1 and 2",
"3 and 4",
"5 and 6",
"7"
You can achieve that using the following function:
_getComponents(list) => list.isEmpty ? list :
([list
.take(2)
.join(' and ')
]..addAll(_getComponents(list.skip(2))));
Call that function like:
List outPut = _getComponents(yourList);
Explanation:
You are declaring a recursive function called _getComponents
As the first statement you are checking whether the parameter list is empty, if it's empty returning the parameter as is
If the list is not empty
You are taking the first 2 items from the list using take function
You are joining those elements using join function
You are calling the addAll function and supplies the result of recursive _getComponents call as it's argument
And as the parameter of that _getComponents function you are passing the list, after skipping the first 2 elements using the skip function
Answer came off the top of my head but try this:
final List list = [1, 2, 3, 4, 5, 6, 7];
List<String> grouped = [];
for (int i = 0; i < list.length; i++) {
if (i % 2 == 0) {
if (i + 1 < list.length) {
grouped.add("${list[i]} and ${list[i + 1]}");
} else {
grouped.add("${list[i]}");
break;
}
}
}
print(grouped);
This works
main(){
final List list = [1,2,3,4,5,6,7];
final List newList = [];
for(int i = 0; i<list.length; i++){
var string;
if(i+1<list.length){
string = "${list[i]} and ${list[i+1]}";
i++;
}else{
string = "${list[i]}";
}
newList.add(string);
}
print(newList);
}
Write this:
void main(){
final List oldList = [1,2,3,4,5,6,7];
final List newList = [];
for(int i = 0; i<list.length; i += 2){
if(i+1<oldList.length){
newList.add("${oldList[i]} and ${oldList[i+1]}");
}else{
newList.add("${oldList[i]}");
}
}
print(newList);
}