Flutter: Return list of Strings using single string in a specific format - flutter

I need to upload array of string to firestore. I need to return list of Strings using single string as input.
If the input is 'Firestore'.
I should return list like this:
[f,fi,fir,firs,first,firsto,firstor,firestore]
If the input is 'Google Cloud'.
I should return list like this:
[g,
go,
goo,
goo,
goog,
googl,
google,
c,
cl,
clo,
clou,
cloud]

For having [g, go, goo, goo, goog, googl, google, c, cl, clo, clou, cloud] as result
use this :
String test = 'Google Cloud';
List<String> chars = [];
for (var word in test.split(" ")) {
for (var i = 0; i <= word.length; i++) {
if (word.substring(0, i).isNotEmpty) {
chars.add(word.substring(0, i));
}
}
}
print(chars);

it's a good practice to share what you have already done. Here is a simple way of achieving what you want (excluding white spaces) :
String test = 'firestore';
List<String> chars = [];
for (var i = 0; i <= test.length; i++) {
if (test.substring(0, i).isNotEmpty) {
chars.add(test.substring(0, i));
}
}
print(chars);
The above prints [f, fi, fir, fire, fires, firest, firesto, firestor, firestore]

Related

how can I check if any word of a string matches a word in a given list?

for example if I have a string = "I Like To Play Football" and a list = [Car,Ball,Door,Sky] it should give true.
Use any of list
var list = ["Car","Ball","Door","Sky"];
String text = "i like to play football";
if (list.any((item) => text.toLowerCase().contains(item))) {
//Text has a value from list
}
Here You Go:
void main() {
final String tempString = "I Like To Play Football";
final List<String> tempList = ["Car","Ball","Door","Sky"];
for(var i=0; i < tempList.length; i ++) {
if(tempString.contains(tempList.elementAt(i).toLowerCase())){
print("Found and its ${tempList[i]}");
}
}
}
Regex is your friend here. You can make a simple regex that uses each string in the array as an option (and make it case insensitive) then run the match. I've made an example here in javascript, but it's easy to do in dart
https://api.dart.dev/stable/2.16.1/dart-core/RegExp-class.html
const source = "I Like To Play Football";
const toMatch = ["Car","Ball","Door","Sky"];
let regexString = '';
for (const option of toMatch) {
//adding | modifier after string. Last one is redundant of course
//also I'm not checking for special regex characters in toMatch, but that might be necessary.
regexString += option + '|';
}
// using slice to remove last |
console.log(regexString.slice(0, -1));
const regexp = new RegExp(regexString.slice(0, -1), 'i');
console.log(source.match(regexp));
Here's a short version:
var src = 'I Like To Play Football'.split(' ');
var list = ['Car','Ball','Door','Sky'];
var result = list.any((x) => src.any((y) => y.toLowerCase().contains(x.toLowerCase())));
print(result);

How to Extract Strings from Text

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]);
}
}

get all the naturals less than a number in ascending order

I'm making a quiz app, and the options are storage this way:
option1 = 'First option'
option2 = 'Second option'
option3 = 'Third option'
numberOfOptions = 3
As some questions will have 4 alternatives, others 2, I'm trying to create a method to dynamically retrieve the number of alternatives available.
For that, I have the numberOfOptions variable. Based on this number, I need to get all the natural numbers less than it until 1 (as in the example, [1, 2, 3]), where I need to add to 'option'. The final result must be:
['option1', 'option2', 'option3'];
For now, what I did was:
void options() {
int numberOfOptions = 3;
for (int i = 0; i < numberOfOptions; i++) {
print('option${i + 1}');
}
}
On the output I get option1, option2, option3, but I'm stuck trying to return it as a List
One elegant solution would be to make use of the List.generate() constructor and achieve our objective with just one line:
List<String>.generate(numberOfOptions, (int index) => 'option${index + 1}');
The List.generate() constructor takes two arguments:
length;
a generator function that has an index variable;
You can read more about it on the official documentation.
It can be useful as it's much easier to read and leaner than a for-loop.
As outlined by #jamesdlin, another option would be to use the collection-for:
List<String> options = [
for(int i = 0; i < numberOfOptions; i++) 'option${i + 1}'
];
You need to create a list in your options() functions and fill it in the foor loop like so:
List<String> options(int numberOfOptions) {
final List<String> options = [];
for (int i = 0; i < numberOfOptions; i++) {
print('option${i + 1}');
options[i] = 'option${i + 1}';
}
return options;
}

Find the most used word in the text in flutter

I'm calculating how many different words there are. How can I find the most used word in the text. How can I add this to the code.
int kacFarkliKelime(String metin) {
String yeniMetin = metin.replaceAll(RegExp(r'[^\w\s]+'), "");
List<String> liste = yeniMetin.split(
" ",
);
List farklilar = [];
liste.forEach((element) {
String sorgulanan = element.toLowerCase();
if (!farklilar.contains(sorgulanan)) {
farklilar.add(sorgulanan);
}
});
if(farklilar[0])
return farklilar.length;
}
I'd build a Map<String, int> that'd count each word as it is seen, then get a list of keys sorted by descending value order. (There's a few handy "sort by" functions in package:collection to help with that.) The code for that would look like:
var words = (use a regex to extract words);
var count = <String,int>{};
for (final w in words) {
count[w] = 1 + (count[w] ?? 0);
}
var ordered = count.keys.toList();
ordered.sort((a, b) => count[b].compareTo(count[a]));
Now the first element of ordered is the word with the most appearances in the text.

How to shuffling the order of a list from snapshot.docs from Stream in firestore [duplicate]

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]