Flutter: check if a list contains only a certain value - list

I need to know if there are only string equals to "Validated" in the list, how can I check it in 1 line of code ?
(If the list is empty, I already checked the condition before so this particular case isn't important).
List<String> state_str_list = ["Validated", "Draft", "Draft", "Waiting", "Validated"];
if (???) {
print("all values in state_str_list are equals to 'Validated' !");
}

Thanks to you, I came to this:
contains_only(var _list, var e) {
_list.every((element) => element == e);
}
print(contains_only(["Validated", "Draft", "Draft", "Waiting", "Validated"], "Validated"));

Related

My condition doesnt work apprpraite in flutter for string

I have a list that stored by sqflite in flutter app, when i open the page i run this code in initState method to produce elements :
String _val_s_list=values_list_r.map((e) => e!=null ? e.s_redio_q : ' ').toString();
print("val_s_list: $_val_s_list"); printed: ///val_s_list: (1)
///method to return a string
choosen_radio_s(_val_s_list);
out of init state defined method as below:
String val_s;
String choosen_radio_s(_val_s_list){
setState(() {
if(_val_s_list=="1"){
return val_p1="1";
}
else{
return val_p1="2";
}
});
}
///print: val_s: 2
but i can not understand why this is not currect on first condition and always returns val_p1="2",
could some one help me about it??

Prevent item in list get deleted

I assign the onValue to two variables in initState.
_boc.selectList(locationId).then((onValue) {
list = onValue;
filterList = onValue;
setState(() {});
});
When it comes to this function, I clear the filterList, but the length of the list become 0.
Future<List<Obk>> getSuggestion(
String search) async {
if (search == "empty") return [];
if (search == "error") throw Error();
filterList.clear();
print(list.length); // this print 0
});
...
}
but if I remove this line filterList = onValue; , it will show the length of the list.
How to prevent the items in list from deleted?
Instead of assigned the same List Object to both list and filteredList. You can make a new list object using List.from(). So that your original List remains unchanged.
_boc.selectList(locationId).then((onValue) {
list = onValue;
filterList = List.from(onValue);
setState(() {});
});
Now if you try to run your code and print the list length then you'll not get 0 after calling filterList.clear().
Future<List<Obk>> getSuggestion(
String search) async {
if (search == "empty") return [];
if (search == "error") throw Error();
filterList.clear();
print(list.length); // this will print list length
});
...
}

How to iterate a class?

UPDATES
This is my final codes just in case anyone needs it:
int index = -2; //I am not 100% sure why I need to start -2, but I assume that `forEach((item){})` probably increase `index` by one, and I also increase `index` inside of the loop, so that's probably why.
recyclable.forEach((item) {
index++;
if (item.title == _outputs[0]["label"]) {
//your code for when the match is found
//move to the detailed page to show more description
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(recyclable: recyclable[index]),
),
);
}
}
END OF UPDATES
I created a class named Recyclable, and using the class, I created a list named recyclable. The list recyclable has a string named title, and I am trying to iterate that title to find a match with _outputs[0]["label"].
To do it, I tried the following code:
while (_outputs[0]["label"] != recyclable[index].title) {
index++;
}
Somehow, there was a red underline for index, which I have no idea why.
I also tried for loop as below to remove that red underline by removing index from my code:
for (var _outputs[0]["label"] in recyclable.title) {
index++;
}
But the code seems to be completely off.
FYI, Here is my class Recyclable:
class Recyclable {
final String title;
final String description;
final String instruction;
final String why;
final String
recycle; //put either "recyclable" or "not recyclable" (This item "can be recycled")
final String
donate; //put either "can be donated" or "cannot be donated" (This item "can be donated")
Recyclable(this.title, this.description, this.instruction, this.why,
this.recycle, this.donate);
}
And here is the list:
List<Recyclable> recyclable = [
Recyclable('PAPERS', 'abc2', 'instruction123', 'why123', 'recyclable',
'cannot be donated'),
Recyclable('CLOTHING', 'abc3', 'instruction123', 'why123', 'recyclable',
'can be donated'),
Recyclable('CARDBOARDS', 'abc4', 'instruction123', 'why123',
'can be recycled', 'cannot be donated'),
Recyclable('COMPUTERS', 'abc4', 'instruction123', 'why123', 'recyclable',
'can be donated'),
];
One way you can iterate over the recyclable list is like this using forEach method
recyclable.forEach((item){
if(item.title == _outputs[0]["label"]){
//your code for when the match is found
}
});

dart - how do check id/name if contains in List?

I have a case when the user wants to add a product to the cart, before that I want to check the id/name product whether or not he was in the cart.
if not then I will add it to the cart, if its already there I will just do edit (adding qty and price)
I have tried using the code below:
Future checkIfProductHasAdded(String uid) async {
for (var i = 0; i < _checkoutList.length; i++) {
print(_checkoutList[i].name);
if (_checkoutList[i].productName == getSelectedProduct.name) {
selectedProductCheckout(i);
print(getSelectedProduct.name +
"PRODUCT CHECKOUT HAS ADDED" +
_checkoutList[i].productName);
// await updateProductCheckout(uid);
break;
} else {
print(getSelectedProduct.name + "NOT FOUND AT PRODUCT CHECKOUT");
//await addProductToCheckout(uid);
break;
}
}
}
when I print() value i does not specify the position on the List, but stays in position 0.
how to make it work?
any answer will be appreciated.
You should check if a product exists in firstWhere clause.
Something like this:
var product = _checkoutList.firstWhere((product) => product.productName == getSelectedProduct.name, orElse: () => null);
if (product == null) addProductToCheckout(uid);
else updateProductCheckout(uid);
This solution is the quickest :
final bool _productIsInList =
_checkoutList.any((product) => product.name == getSelectedProduct.name);
if (_productIsInList) {
// The list contains the product
} else {
// The list does not contain the product
}
NOTE :
If you don't need to compare IDs/names, but you just want to check if a specific item is in a list, you can use _checkoutList.contains(item)

Index of string containing a part of string (one word)

im trying to read a large file, so i thought that instead of looping with an array i decided to use a list, but I'm having some difficulties with searching a line which contains a word that needs to be searched for. Here is my code
public List<string> AWfile = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
if (File.Exists(#"C:\DataFolder\file.txt"))
{
using (StreamReader r = new StreamReader(#"C:\DataFolder\file.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
AWfile.Add(line); label1.Text = "ListWritten!"; label1.BackColor = Color.Green;
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
int linen = AWfile.IndexOf("A102");
label2.Text = Convert.ToString(linen);
}
So my question is if there is any way to search just for a part of a word in a list instead of the whole string, because that's the only way the .IndexOf returns me anything at all.
You can try something like:
var result = list.Select(x => x.Contains("hello")).ToList()
This will result in a list with all the elements in the list which contains "hello".
And if you want to do something only with this elements:
list.Select(x => x.Contains("hello")).ToList().ForEach(x => DoSomething(x));
I hope this helps
If I understand your question correctly... you are reading in a file and adding each line to a list. Then you want to check if any of those lines contain part of a word.
One way of doing this would be to do a foreach loop over each of the lines in your list and checking if the line contains the partial word.
Something like:
foreach(var line in AWFile)
{
if(line.Contains("PartialWordWeWant"))
{
// Do something with the line that contains the word we are looking for
}
}