I am reading a text file consisting of several lines, each line contains two numbers, one of them expresses the user name and the other expresses the password, the text appears as follows:
7829-613
2076-386
3001-007
5916-477
9782-858
3928-345
3574-189
I changed - to : by this code:
text= text.replaceAll('-', ':');
The result is :
7829:613
2076:386
3001:007
5916:477
9782:858
3928:345
3574:189
I tried to replace \n to , by this code:
text= text.replaceAll('-', ':')..replaceAll('\n',',');
So that I can separate each line, key and value, but not work
Is there any way to get Mapfrom this text
Thanks advance
Try this
var text = "7829-613\n2076-386\n3001-007\n5916-477\n9782-858\n3928-345\n3574-189";
text = text.replaceAllMapped(RegExp(r"[0-9]{3,4}"), (match) => "\"${match.group(0)}\"");
text = text.replaceAll("-", ":");
text = text.replaceAll("\n", ",");
var map = jsonDecode("{$text}");
print(map);
Just use a r before to the String to read raw special characters.
String text = r'mmmmm\nssdsds\n';
text = text.replaceAll(r'\n', ',');
Before you open your file, you can declare final credentials = Map<String, dynamic>.
Then, you can iterate through each line of the file with an input stream as in https://api.dart.dev/stable/2.9.2/dart-io/File-class.html.
That is the following, where in each line you split the string by the colon(:) separator and assign those key value pairs to the map:
import 'dart:io';
import 'dart:convert';
import 'dart:async';
main() {
final credentials = Map<String, dynamic>
final file = new File('file.txt');
Stream<List<int>> inputStream = file.openRead();
inputStream
.transform(utf8.decoder) // Decode bytes to UTF-8.
.transform(new LineSplitter()) // Convert stream to individual lines.
.listen((String line) { // Process results.
final decodedLine = line.split(":");
credentials[decodedLine[0]] = credentials[decodedLine[1]];
},
onDone: () { print('File is now closed.'); },
onError: (e) { print(e.toString()); });
}
Please let me know if you have any questions about this. I tried to be as thorough as I could :)
Related
Looking for the same solution that was given in swift here - How to remove first word from a sentence in swift.
Anyone can help?
void main() {
String words = "hello world everyone";
List<String> word_l = words.split(" ");
String word = word_l.sublist(1,word_l.length).join(" ");
print(word);
}
Use as above code to remove first word from words. This work for multiple words more than 2.
You could just do this:
void main() {
var data = 'CITY Singapore';
data = data[0];
print(data);
}
i have saved list of images to database in blob format and retriving it as well everything works well but i want to get all the images of database and convert it to list of file. in database i am saving list of images but seperating the images with comma like this :- image1,image2 but all image are in blob format now i want to retrive that image and convert that images to file and store it to my own list but so far i am only able to convert the first image of list and not other
List<File> imagesData = [];
Future<String> getImages()async {
imagesData.clear();
if (savedHomeworkImages != null) {
for (int i = 0; i < savedHomeworkImages.split(",").length; i++) {
if (savedHomeworkImages.split(",")[i].length > imagesData.length) {
Uint8List bytes = base64.decode(savedHomeworkImages.split(",")[1]);
String dir = (await getApplicationDocumentsDirectory()).path;
File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ".jpg");
file.writeAsBytesSync(bytes);
setState(() {
imagesData.add(File(file.path));
});
print("This is images Data $imagesData");
return file.path;
}
}
}
}
#this is how i am trying to convert blob image to file but i am not able to convert list of blob to list of file need some guidence thanks
convert our Image file to bytes with the help of dart:io library.
import 'dart:io' as Io;
final bytes = await Io.File(image).readAsBytes();
// or
final bytes = Io.File(image).readAsBytesSync();
use dart:convert library base64Encode() function to encode bytes to Base64.
It is the shorthand for base64.encode().
String base64Encode(List<int> bytes) => base64.encode(bytes);
Lets Say this is My Text. Now I want to Extract All 4 Variable Separately from the text
"ScanCode=? scanMsg= ? ItemName=? ID= ?\n"
Please Help i need this is Dart, Flutter
The solution I developed first splits the data according to the space character. It then uses the GetValue() method to sequentially read the data from each piece. The next step will be to use the data by transforming it accordingly.
This example prints the following output to the console:
[ScanCode=1234, ScanMessage=Test, Itemname=First, ID=1]
[1234, Test, First, 1]
The solution I developed is available below:
void main()
{
String text = "ScanCode=1234 ScanMessage=Test ItemName=First ID=1";
List<String> original = text.split(' ');
List<String> result = [];
GetValue(original, result);
print(original);
print(result);
}
void GetValue(List<String> original, List<String> result)
{
for(int i = 0 ; i < original.length ; ++i)
{
result.insert(i, original[i].split('=')[1]);
}
}
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 :)
I want to enter a array like [1,2,3,4,5] in the form field and use that form value as a parameter to bubblesort function to sort the array.How to implement this in flutter?
Keep it simple and just use the builtin json parser.
Like this:
List<int> nbs = List<int>.from(json.decode('[1,2,3,4]'));
Our string:
final hi = "[1,2,3,4,5]";
The regular expression used to remove the square brackets:
final regex = RegExp(r'([\[\]])');
Our string without any brackets after replacing them with nothing:
final justNumbers = hi.replaceAll(regex, ''); // 1,2,3,4,5
Our list of strings by splitting them by commas:
List<String> strings = justNumbers.split(',');
Now we parse our strings into integers (tryParse is used so that it returns null instead of throwing an exception):
List<int> numbers = strings.map((e) => int.tryParse(e)).toList();
Final
void main() {
final hi = "[1,2,3,4,5]";
final regex = RegExp(r'([\[\]])');
final justNumbers = hi.replaceAll(regex, '');
List<String> strings = justNumbers.split(',');
List<int> numbers = strings.map((e) => int.tryParse(e)).toList();
print(numbers);
}