Flutter convert string in list double - flutter

I have a response from REST API that return this:
var time = [{"duration":"00m 25s"},{"duration":"12m 08s"},{"duration":"02m 09s"},{"duration":"01m 25s"}, {"duration":"02m 05s"}]
I want to transform this list in:
var newTime = [0.25, 12.08, 2.09, 1.25, 2.05]

You can do string manipulation using splitting string using some delimiter like space and applying transformation via map.
void main() {
var time = [
{"duration": "00m 25s"},
{"duration": "12m 08s"},
{"duration": "02m 09s"},
{"duration": "01m 25s"},
{"duration": "02m 05s"}
];
time.map((e) {
final val = e['duration'].split(' '); // split by space
final result = val[0].substring(0, val[0].length - 1) + '.' +
val[1].substring(0, val[1].length - 1); // concat number by removing unit suffix
return double.tryParse(result); // parsing to double.
}).forEach((e) => print(e)); // 0.25, 12.08, 2.09, 1.25, 2.05
}

You can do it as follows:
var time = [{"duration":"00m 25s"},{"duration":"12m 08s"},{"duration":"02m 09s"},{"duration":"01m 25s"}, {"duration":"02m 05s"}];
var newList = time.map((time) {
String clippedMinutes; // will get the minutes part
String clippedSeconds; //// will get the seconds part
String fullTime = time['duration']; // full time part from each Map
final splittedTimeList = fullTime.split(' '); // splits the full time
clippedMinutes = splittedTimeList[0];
clippedSeconds = splittedTimeList[1];
return double.parse('${clippedMinutes.substring(0, clippedMinutes.length - 1)}.${clippedSeconds.substring(0, clippedSeconds.length - 1)}');
}).toList();
print(newList); // output: [0.25, 12.08, 2.09, 1.25, 2.05]
If it helped you don't forget to upvote

My contribution:
main(List<String> args) {
final times = [{"duration":"00m 25s"},{"duration":"12m 08s"},{"duration":"02m 09s"},{"duration":"01m 25s"}, {"duration":"02m 05s"}];
var regExp = RegExp(r'(\d\d)m (\d\d)s');
var newData = times.map((e) => double.parse(e['duration'].replaceAllMapped(regExp, (m) => '${m[1]}.${m[2]}')));
print(newData);
}
Result:
(0.25, 12.08, 2.09, 1.25, 2.05)

Related

How to extract specific string from whole string?

I have following strings :
String? hello = "(1.2,1.5 | 5)"
String? hi = "(2.3,3.2 | 9)"
Now I want to get
var newhello1 = 1.2,1.5
var newhello2 = 5
and
var newhi1 = 2.3,3.2
var newhi2 = 9
How to extract those text from that entire strings?
You can use the indexOf function combined with the substring to get the substrings as follows
var newhello1 = hello.substring(hello.indexOf('(') + 1, hello.indexOf('|')).trim(); //Use Trim() to get rid of any extra spaces
var newhello2 = hello.substring(hello.indexOf('|') + 1,hello.indexOf(')')).trim();
print(newhello1); //1.2,1.5
print(newhello2); //5
List<String> myformatter(String? data) {
if (data == null) return [];
List<String> ls = data.split("|");
for (int i = 0; i < ls.length; i++) {
ls[i] = ls[i].replaceAll("(", "").replaceAll(")", "").trim();
}
return ls;
}
main() {
String? hello = "(1.2,1.5 | 5)";
String? hi = "(2.3,3.2 | 9)";
final helloX = myformatter(hello);
print(helloX[0]); //1.2,1.5
print(helloX[1]); //5
final hiX = myformatter(hi);
print(hiX[0]); //2.3,3.2
print(hiX[1]); //9
}

How to split a string in Flutter while also including delimiters

+37.4054-122.0999/
The above coordinates are my output. I want to split the string in such a way that it shows +37.4054 and -122.0999 as substrings which includes the + and - signs.
You can do
string.split(RegExp('(?=[+-])'));
Example:
var string = '+37.4054-122.0999';
var string2 = '-37.4054+122.0999';
var string3 = '+37.4054+122.0999';
var string4 = '-37.4054-122.0999';
var a = string.split(RegExp('(?=[+-])'));
var b = string2.split(RegExp('(?=[+-])'));
var c = string3.split(RegExp('(?=[+-])'));
var d = string4.split(RegExp('(?=[+-])'));
print(a);
print(b);
print(c);
print(d);
Output:
[+37.4054, -122.0999]
[-37.4054, +122.0999]
[+37.4054, +122.0999]
[-37.4054, -122.0999]
Try use split method:
const string = '+37.4054-122.0999';
final splitted = string.split('-');
print(splitted); //['+37.4054', '122.0999'];
print(splitted[0]); //+37.4054;
print('-' + splitted[1]); //-122.0999;
Try this:
void main() {
final String coord = '+37.4054-122.0999';
final int plusIndex = coord.indexOf('+');
final int minusIndex = coord.indexOf('-');
final plus = coord.substring(plusIndex, minusIndex);
final minus = coord.substring(minusIndex, );
print('plus: $plus, minus: $minus');
}

split the string into equal parts flutter

There is a string with random numbers and letters. I need to divide this string into 5 parts. And get List. How to do it? Thanks.
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
Should work:
List<String> list = [
'05b37ffe',
'4973959c',
'4d4f2d5c',
'a0c14357',
'49f8cc66',
];
I know there'a already a working answer but I had already started this so here's a different solution.
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
List<String> list = [];
final divisionIndex = str.length ~/ 5;
for (int i = 0; i < str.length; i++) {
if (i % divisionIndex == 0) {
final tempString = str.substring(i, i + divisionIndex);
list.add(tempString);
}
}
log(list.toString()); // [05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
int d=1
; try{
d = (str.length/5).toInt();
print(d);
}catch(e){
d=1;
}
List datas=[];
for(int i=0;i<d;i++){
var c=i+1;
try {
datas.add(str.substring(i * d, d*c));
} catch (e) {
print(e);
}
}
print(datas);
}
OR
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
int d = (str.length / 5).toInt();
var data = List.generate(d - 3, (i) => (d * (i + 1)) <= str.length ? str.substring(i * d, d * (i + 1)) : "");
print(data);//[05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]
If you're into one liners, with dynamic parts.
Make sure to import dart:math for min function.
This is modular, i.e. you can pass whichever number of parts you want (default 5). If you string is 3 char long, and you want 5 parts, then it'll return 3 parts with 1 char in each.
List<String> splitIntoEqualParts(String str, [int parts = 5]) {
int _parts = min(str.length, parts);
int _sublength = (str.length / _parts).ceil();
return Iterable<int>
//Initialize empty list
.generate(_parts)
.toList()
// Apply the access logic
.map((index) => str.substring(_sublength * index, min(_sublength * index + _sublength, str.length)))
.toList();
}
You can then use it such as print(splitIntoEqualParts('05b37ffe4973959c4d4f2d5ca0c1435749f8cc66', 5));
splitWithCount(String string,int splitCount)
{
var array = [];
for(var i =0 ;i<=(string.length-splitCount);i+=splitCount)
{
var start = i;
var temp = string.substring(start,start+splitCount);
array.add(temp);
}
print(array);
}

How to format to json with difference between comma of data/key and comma from text?

I am trying to improve this code so that it can handle a specific case.
Currently it works, unless the user adds a text with a comma
Here is my input who work (look only "note" key/value)
Input_OK = 2020-11-25,note:my text,2020-11-25,today:2020-11-25,2020-09-14,start:2020-09-14
In this case : my text is ok because there is no comma
Input_NOK = 2020-11-25,note:my text, doesn't work,2020-11-25,today:2020-11-25,2020-09-14,start:2020-09-14
In this case : my text, doesn't work is not ok because there is comma
With this specific input 2020-11-25,note:my text, work now,2020-11-25,today:2020-11-25,2020-09-14,start:2020-09-14
I try to have this output
[{"release_date":"2020-11-25","today":"2020-11-25","note0":"my text, work now"},{"release_date":"2020-09-14","start":"2020-09-14"}]
Here is my current code
// before this input I add string to a list<String> for each date like that [2020-11-25,note0:test, 2020-11-24,my text, with comma, 2020-11-15,today:2020-11-15, 2020-09-14,start:2020-09-14]
//After I remove space and [ ]
// myinput 2020-11-25,today:2020-11-25,2020-11-25,note0:my text, with comma,2020-09-14,start:2020-09-14
var inputItarable = myinput.toString().split(',').where((s) => s.isNotEmpty);
print("inputItarable ${inputItarable} ");
//inputItarable [2020-11-25, today:2020-11-25, 2020-11-25, note0:my text, with comma, 2020-09-14, start:2020-09-14]
var i = inputItarable.iterator;
var tmp = {};
while (i.moveNext()) {
var key = i.current; i.moveNext();
var value = i.current.split(':');
(tmp[key] ??= []).add(value);
}
var output1 = tmp.keys.map((key) {
var map = {}; map['release_date'] = key;
tmp[key].forEach((e) => map[e[0]] = e[1]);
return map;
}).toList();
var output2=json.encode(output1);
print("output2 $output2 ");
// output2 [{"release_date":"2020-11-25","today":"2020-11-25","note0":"my text, with comma"},{"release_date":"2020-09-14","start":"2020-09-14"}]
[Edit] I have a spécific case, where user back ligne, and have an input like that
myinput 2020-11-25,today:2020-11-25,2020-11-25,note0:my text,
with comma,2020-09-14,start:2020-09-14
in this example I don't know how to replace the back ligne between my text, and with comma by my text,\nwith comma
Please check the code below or you may directly run it on Dartpad at https://dartpad.dev/1404509cc0b427b1f31705448b5edba3
I have written a sanitize function. What the sanitize function does is it sanitizes the text between the possibleStart and possibleEnd. Meaning it replaces all the commas in user input text with §. To do this it assumes that the user input starts with ,note: or ,note0: and ends with ,2020- or ,2021-. This sanitized string is passed to your code and in the end § is replaced with ",". Let me know if you have any questions.
import 'dart:convert';
String sanitize(
String input, List<String> possibleStart, List<String> possibleEnd) {
final String start = possibleStart.join("|");
final String end = possibleEnd.join("|");
final RegExp exp = RegExp("(?<=$start)(.*?)(?=$end)");
final Iterable<Match> matches = exp.allMatches(input);
matches.forEach((match) {
input =
input.replaceFirst(match.group(0), match.group(0).replaceAll(",", "§"));
return true;
});
return input;
}
void main() {
String myinput =
"2020-11-25,today:2020-11-25,2020-11-25,note0:my text, with comma,2020-09-14,start:2020-09-14";
myinput = sanitize(myinput, [",note:", "note\\d:"], [",20\\d\\d-"]);
var inputItarable = myinput.toString().split(',').where((s) => s.isNotEmpty);
print("inputItarable ${inputItarable} ");
//inputItarable [2020-11-25, today:2020-11-25, 2020-11-25, note0:my text, with comma, 2020-09-14, start:2020-09-14]
var i = inputItarable.iterator;
var tmp = {};
while (i.moveNext()) {
var key = i.current;
i.moveNext();
var value = i.current.split(':');
(tmp[key] ??= []).add(value);
}
var output1 = tmp.keys.map((key) {
var map = {};
map['release_date'] = key;
tmp[key].forEach((e) => map[e[0]] = e[1]);
return map;
}).toList();
var output2 = json.encode(output1).replaceAll("§", ",");
print("output2 $output2 ");
}

Converting a List of DateTime into Strings

I'm trying to covert a list of dates into a string
var list = <DateTime>[];
DateTime start = DateTime(2019, 12, 01);
final end = DateTime(2021, 12, 31);
while (start.isBefore(end)) {
list.add(start);
start = start.add(const Duration(days: 1));
}
list.map((DateTime time) {
var dateRange = DateFormat("MM-dd-yy").format(time);
List<String> userSearchItems = [];
userSearchItems.add(dateRange);
print(userSearchItems);
});
but userSearchItems is coming up as empty
The code block inside list.map is never executed.
This is because list.map produces a lazy transformation of the list. The transformation function is executed only when elements are requested from it.
You probably want to use:
var dates = list.map((DateTime time) {
var dateRange = DateFormat("MM-dd-yy").format(time);
return dateRange;
});
print(dates);
In the code above, it is the print function that forces the transformation to run.
Alternatively, you can transform the result of the list.map to a list using
var datesList = dates.toList();
Again, this forces eager evaluation of the map transformation.