In this list, I want to display out all the items that contains this specific name.
My list items: ['US', 'SG', 'US']
print(list.contains("US"));
Using .contains() returns me a true or false but it doesn’t return me the list of strings that contains that. I want to only extract out the items that has 'US' from the list. In this case, there's 2 of it. Please help!
You can try doing it the following way -
List<String> myList = ['US', 'SG', 'US'];
print(myList.where((item) => item.contains("US")));
You can also display it directly inside a Text widget in the following way -
Text(
myList.where((item) => item.contains("US")).join(" "),
//The join function joins the elements of the Iterable into a single string with the separator provided as an argument.
),
Hope this helps!
UPDATE:
To display each of the word separately as a list you can display them inside a Column in the following way -
Column(
children: myList.map((value) {
if(value.contains("US")){
return Text(value,);
} else {
return Container();
//Return an empty Container for non-matching case
}
}).toList(),
)
The same thing can be used inside a ListView instead of Column if you want it to be scrollable.
Something like this?
var myList = ['US', 'SG', 'US'];
myList.forEach((w){
if(w == "US")
print(w);
});
To show:
class SO extends StatelessWidget {
var myList = ['US', 'SG', 'US'];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisSize: MainAxisSize.min,
children: myList.where((w) => w == "US").map((w) => Text(w)).toList(),
),
);
}
}
or for a single line display use, Text instead of Column widget mentioned above
Text(myList.where((w) => w.contains("US")).join(" "))
If you are using "list.contains". It will only show the list exist or not , If you want to print the value you have to use follow :
var fruits = [‘banana’, ‘pineapple’, ‘watermelon’];fruits.forEach((fruit) => print(fruit)); // => banana pineapple watermelon
If you want to print just banana then you can use this
var fruits = [‘banana’, ‘pineapple’, ‘watermelon’];fruits.(fruit) => print(fruit[0]); // => banana
Related
So I have a list of predefined choices that I defined below
final List<DropdownMenuItem> grades = <DropdownMenuItem>[
DropdownMenuItem(value: "Highschool", child: Text('Highschool')),
DropdownMenuItem(value: "Senior High", child: Text('Senior High')),
DropdownMenuItem(value: "College", child: Text('College'))];
And what I want to do is traverse through the list and put it under the drop down menu
Form(
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
value: defState,
onChanged: (String? newValue) {
setState(() {
defState = newValue!;
});
},
items: grades.map((items) => return items),
hint: Text("Grade"),
),
)),
)
But it's giving me these two errors
The argument type 'Iterable<DropdownMenuItem<dynamic>>' can't be assigned to the parameter type 'List<DropdownMenuItem<String>>?'.
Unexpected text 'return'.
Try removing the text.
Is there a way to iterate the list so I can just immediately return?
A few things:
First, arrow functions don't need the return keyword. For example, the following 2 functions are equivalent:
grades.map((_) => 'hello')
grades.map((_) {
return 'hello';
})
Secondly, the error message says: "you gave me an Iterable<DropdownMenuItem<dynamic>>, but I need a List<DropdownMenuItem<String>>".
You're creating a DropdownButton<String>, which takes a List<DropdownMenuItem<String>> as its items parameter, but you pass in grades.map( ... ).
map() is defined in Iterable, and has the following signature:
Iterable<T> map<T>(T f(E e))
This is a little bit opaque, but crucially, it returns an Iterable<T>, where T is the return type of the function you pass in, for example:
List<int> ints = [1, 2, 3];
Iterable<String> strings = ints.map((i) => i.toString());
To fix your problem, you should do the following:
instead of having a final field with widgets inside, make it a function. You should avoid caching widgets like this (unless they are const) as it interferes with hot-reload. Importantly, the function should also specify the type of DropdownMenuItem it returns:
List<DropdownMenuItem<String>> get grades => [
DropdownMenuItem<String>(...),
...
]
Your map function is invalid, but if you remove the return keyword, it would be (items) => items, which is the identity function (i.e. it does nothing). You can remove this and it will work.
Alternatively, if you want to call some function, you then need to call toList() on the result, since items expects a list:
items: grades,
// or
items: grades.map((grade) => ...).toList(),
Change the type of grades list to List<DropdownMenuItem<String>>:
final List<DropdownMenuItem<String>> grades = [
DropdownMenuItem(value: "Highschool", child: Text('Highschool')),
DropdownMenuItem(value: "Senior High", child: Text('Senior High')),
DropdownMenuItem(value: "College", child: Text('College'))
];
And just use grades instead of a map:
DropdownButton<String>(
value: defState,
onChanged: (String? newValue) {
setState(() {
defState = newValue!;
});
},
items: grades,
hint: Text("Grade"),
),
it's my first post.
I work to Quasar (Vue.js)
I have list of jobs, and in this list, i have words with special caractere.
Ex :
[ ...{ "libelle": "Agent hôtelier" },{"libelle": "Agent spécialisé / Agente spécialisée des écoles maternelles -ASEM-"},{ "libelle": "Agriculteur / Agricultrice" },{ "libelle": "Aide aux personnes âgées" },{ "libelle": "Aide de cuisine" },...]
And on "input" i would like to search "Agent spécialisé" but i want to write "agent specialise" (without special caractere) or the initial name, i want to write both and autocomplete my "input".
I just don't fin the solution for add to my filter code ...
My input :
<q-select
filled
v-model="model"
use-input
hide-selected
fill-input
input-debounce="0"
:options="options"
hint="Votre métier"
style="width: 250px; padding-bottom: 32px"
#filter="filterFn"
>
</q-select>
</div>
My code :
export default {
props: ['data'],
data() {
return {
jobList: json,
model: '',
options: [],
stringOptions: []
}
},
methods: {
jsonJobsCall(e) {
this.stringOptions = []
json.forEach(res => {
this.stringOptions.push(res.libelle)
})
},
filterFn(val, update) {
if (val === '') {
update(() => {
this.jsonJobsCall(val)
this.options = this.stringOptions
})
return
}
update(() => {
const regex = /é/i
const needle = val.toLowerCase()
this.jsonJobsCall(val)
this.options = this.stringOptions.filter(
v => v.replace(regex, 'e').toLowerCase().indexOf(needle) > -1
)
})
},
}
}
To sum up : i need filter for write with or witouth special caractere in my input for found in my list the job which can contain a special character.
I hope i was clear, ask your questions if i haven't been.
Thanks you very much.
I am not sure if its work for you but you can use regex to create valid filter for your need. For example, when there is "e" letter you want to check "e" or "é" (If I understand correctly)
//Lets say we want to match "Agent spécialisé" with the given search text
let searchText = "Agent spe";
// Lets create a character map for matching characters
let characterMap = {
e: ['e', 'é'],
a: ['a', '#']
}
// Replacing special characters with a regex part which contains all equivelant characters
// !Remember replaceAll depricated
Object.keys(characterMap).forEach((key) => {
let replaceReg = new RegExp(`${key}`, "g")
searchText = searchText.replace(replaceReg, `[${characterMap[key].join("|")}]`);
})
// Here we create a regex to match
let reg = new RegExp(searchText + ".*")
console.log("Agent spécialisé".match(reg) != null);
Another approach could be the reverse of this. You can normalize "Agent spécialisé". (I mean replace all é with normal e with a regex like above) and store in the object along with the original text. But search on this normalized string instead of original.
I want to have a Scaffold, which contains a variable amount of Elements in a ListView. The Elements are all equal, just a few values are different. So I made a Scaffold for those Elements and want to store them in a growable List. My Problem is, that the AnimatedSwitcher doesn't work anymore when I retrieve it from the List.
bool Boolean = false; <br/>
List<Widget> widgets = [ AnimatedSwitcher(<br/>duration: Duration(seconds: 2), <br/>child: Boolean ? childrenOne : childrenTwo) ]
body: ListView( <br/>
children: widgets
),
I'm having issues simply printing what's inside a DropdownButton by looping the results of an API request that fetches the following:
[{id: 1, nome: foo}, ...]
This is the code for it.
return _response.data.map<Client>((i) => Client.fromJson(i)).toList();
Which oddly, when printing the variable that stores the above call is [Instance of 'Client', ...]
Then, in the view, I attempt to at least print each item:
DropdownButton<Client>(
onChanged: (client) => print(client),
items: _controller.clients
.map(
(i) => print(i),
)
.toList(),
But type 'List<void>' is not a subtype of type 'List<DropdownMenuItem<Client>>'. I am lost already.
Where you are printing i, you instead need to be returning a DropDownMenuItem (with a child)
For example:
items: _controller.clients.map((e) => DropDownMenuItem(value: e, child: Text(e.nome))).toList(),
I have a Master/Child grid structure like so:
Parent Grid:
#(Html.Kendo().Grid<ElementViewModel>()
.Name("gridEle")
.Columns(cols =>
{
cols.Bound(e => e.EleNum)
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetElements", "Rating", pi))
)
.ClientDetailTemplateId("tempSubEle")
)
Child Grid as DetailTemplate:
<script id="tempSubEle" type="text/kendo-tmpl">
#(Html.Kendo().Grid<SubElementViewModel>()
.Name("gridSubEle_#=EleID#")
.Columns(cols =>
{
cols.Bound(e => e.Rating)
.ClientTemplate("<input type='checkbox' value='1' " +
"#if(Rating==1){#checked='checked'#}# />" );
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetSubElementsByElementID", "Rating", new {eID = "#=EleID#" }))
)
.ToClientTemplate()
)
</script>
The Problem:
I have a #if{# ... #}# statement in the column ClientTemplate, however the Rating value is from the Parent Grid not the current Child Grid (Parent Grid happen has a column also named 'Rating'), to prove that it is from Parent Grid, if I change Rating to a column that only exists in the Child grid, i.e. SubEleID, it gives error at browser, saying that SubEleID is not found.
The Question:
so what is the syntax for Rating gets the Child Grid value?
just for the sake of trying, I even tried: data.Rating, or $(this).Rating, none worked.
Please advise,
Thank you
# in some kendo template is used for parent property (like you use for the name : gridSubEle_#=EleID#, but for some child property, you have to escape the # with \\ :
cols.Bound(e => e.Rating)
.ClientTemplate("<input type='checkbox' value='1' " +
"\\#if(Rating==1){\\#checked='checked'\\#}\\# />" );