How can make checkbox select and multiple selection with Getx - flutter

my code is without button that make select all
View class
GetBuilder<ProductController>(
builder: (controller) {
return
Container(
height: 50,
child: Transform.scale(
scale: 1.2,
child: Checkbox(
activeColor: MyThemes.yellow,
shape:RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5)
),
splashRadius: 18.8,
value: controller.items[index]["check"],
onChanged:((value) {
controller.CheckBrand(index, value);
}
)),
),
);}),
controller class
RxList<Map<String,dynamic>> items = [{"one": "Item1", "check": false},
{"one": "Item2", "check": false}, {"one": "Item3", "check": false}].obs;
CheckBrand(index, ischeck){ items[index]["check"]=ischeck; update(); }
I want to ask is there another way to make checkbox selection and how can I make select all button for this items

you can iterate over elements to check them all at once, you can use this method:
void checkAll({bool newValue = true}) {
items.value.forEach((element) {
element["check"] = newValue;
});
update();
}
I will add also a method that uncheck all at once:
void unCheckAll() {
checkAll(newValue: false);
}
now from your view, just call it like this:
controller.checkAll(); // will check all check boxes
controller.unCheckAll(); // will uncheck all check boxes

Related

The element type 'List<DropdownMenuItem<double>>' can't be assigned to the list type 'DropdownMenuItem<double>'

I'm having a problem when ı try to automatize my Items which is a part of DropDownButton.
Every time ı try to execute the function below ı get this error:The element type 'List<DropdownMenuItem>' can't be assigned to the list type 'DropdownMenuItem'.
I tried not to use map function and did the same as Flutter's official page that describes how to use a dropdown button but nothing has changed. I got the same error.
class DataHelper {
static List<String> tumDerslerinHarflerii() {
return ["AA", "BA", "BB", "CB", "CC", "CD", "DD", "FD", "FF"];
}
static double? harfiNotaCevir(String harf) {
switch (harf) {
case "AA":
return 4;
case "BA":
return 3.5;
case "BB":
return 3.0;
case "CB":
return 2.5;
case "CC":
return 2;
case "DC":
return 1.5;
case "DD":
return 1.0;
case "FD":
return 0.5;
case "FF":
return 0.0;
}
return null;
}
static List<DropdownMenuItem<double>> tumDerslerinHarfleri() {
return tumDerslerinHarflerii()
.map(
(e) => DropdownMenuItem(
child: Text("$e"),
value: harfiNotaCevir(e),
),
)
.toList();
}
}
And I'm using it in my DropDownWidget:
_buildHarfler(GlobalKey buildHarfKey, double _value) {
return Container(
decoration: BoxDecoration(
color: Sabitler.anaRenk.withOpacity(0.3),
borderRadius: Sabitler.borderRadius,
),
child: DropdownButton<double>(
key: buildHarfKey,
value: _value,
items: [
// Dropdown içindeki elementlerin her biri bir widget; liste istiyor.
DataHelper.tumDerslerinHarfleri(),
],
onChanged: (secilenDeger) {
_value = secilenDeger!;
},
),
);
}
change DataHelper.tumDerslerinHarfleri(), to ...DataHelper.tumDerslerinHarfleri(),
this will add the items in the list that are coming from your function (tumDerslerinHarfleri) to the items of your DropdownButton
You need to spread you list. [...DataHelper.tumDerslerinHarfleri()]

Dynamically add dimensions to boolean array

I'm using flutter to develop an e-commerce app.
I'm working on the navDrawer for it and I could use some help with the categories.
I have categories that can have subcategories and the subcategories can also have their own subcategories.
Basically, the data set is an array of unknown dimensions.
I need to make a boolean map for my categories and subcategories so that I can keep track of which ones are open in order to show the subcategories.
Here's an example of the dataset:
{
"id":"41490",
"name":"Electrical Equipment",
"subCategories":[
{
"id":"41492",
"name":"Breakers",
"subCategories":[
{
"id":"167542",
"name":"1 Pole",
"subCategories":[
{
"id":"167577",
"name":"15 Amp",
"subCategories":null
},
{
"id":"167585",
"name":"20 Amp",
"subCategories":null
},
{
"id":"167600",
"name":"30 Amp",
"subCategories":null
},
{
"id":"167606",
"name":"40 Amp",
"subCategories":null
}
]
},
I think recursion is the optimal way to process this dataset but the problem I'm having is that I can't figure out how to have dynamic dimensions for an array in Dart.
I already figured out how to generate my listTiles from the dataset but I can't figure out the boolean map.
Is this even possible or should I look into a different approach?
Here's my code for generating the listTiles from the dataset:
void setCategories(List categories){
_categories = categories;
int catCount = categories.length;
_categoryList = new ListView.builder(
//shrinkWrap: true,
//physics: ClampingScrollPhysics(),
padding:EdgeInsets.all(0.0),
itemCount: catCount,
itemBuilder: (BuildContext context, int index) => buildCategories(context, index),
);
}
Widget buildCategories(BuildContext context, int index){
if(_categories[index]['subCategories']!=null){
//TODO: call buildSubCategories with depth of 1 parameter
return Container(
height: 30.0,
child: ListTile(
title: Row(
children:[
Text(" "+_categories[index]['name']),
Transform.scale(
scale: 0.75,
child:
Icon(Icons.arrow_back)
)
]
),
onTap: () {
//TODO: implement boolean map here
}
),
padding: EdgeInsets.all(0.0),
margin: EdgeInsets.all(0.0)
);
} else {
return Container(
height: 30.0,
child: ListTile(
title: Text(" "+_categories[index]['name']),
onTap: () {
}
),
padding: EdgeInsets.all(0.0),
margin: EdgeInsets.all(0.0)
);
}
}
Widget buildSubCategories(var parent, int depth){
List subCategoryList = parent['subCategories'];
int subCategoryCount = subCategoryList.length;
if(parent['subCategories']!=null){
//for each subCategory
//if subCategory has subCategories
//recurse subCategory with depth
buildSubCategories(parent['subCategories'], depth++);
//TODO: implement boolean map here
} else {
//
}
}
void generateCategoryBooleanMap(){
//TODO: generate boolean map here
//TODO: boolean map needs to have a undetermined amount of depth levels
}
Any insight is appreciated even if it means I have to use a different paradigm.
Example of using a Set to keep track of which id is open:
void main() {
final idHandler = IdHandler();
print(idHandler.isIdOpen('MyId')); // false
idHandler.openId('MyId');
print(idHandler.isIdOpen('MyId')); // true
idHandler.closeId('MyId');
print(idHandler.isIdOpen('MyId')); // false
idHandler.openId('MyId');
print(idHandler.isIdOpen('MyId')); // true
idHandler.closeAll();
print(idHandler.isIdOpen('MyId')); // false
}
class IdHandler {
final Set<String> _openIds = {};
void openId(String id) => _openIds.add(id);
void closeId(String id) => _openIds.remove(id);
void closeAll() => _openIds.clear();
bool isIdOpen(String id) => _openIds.contains(id);
}

Adding Search function to SliverList in Flutter

I'm trying to add a search function to my SliverList containing multiple list items.
Just before looping through my List of elements I added the TextField to implement the search function itself.
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
onChanged: (value) {
filterSearchResults(value);
},
controller: editingController,
decoration: InputDecoration(
labelText: "Search",
hintText: "Animal Name",
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0))),
),
),
),
for (var animal in response)
Card( /* Elements to be searched later */)
as for the fluterSearchResults function:
void filterSearchResults(String query) {
List response = widget.res; // <- contains the animal data I'd like to search through
List<String> searchList = List<String>();
if (query.isNotEmpty) {
searchList.forEach((response) {
if (response.contains(query)) {
searchList.add(response);
}
setState(() {
items.clear();
items.addAll(searchList);
});
});
return;
} else {
setState(() {
items.clear();
items.addAll(searchList);
});
}
}
one element of the data within widget.res looks like this:
[{
id: 1,
game: "basegame",
name: "Aardvark",
continent: [
"Africa"
],
biome: [
"Grassland",
"Tropical"
],
can_swim: true,
status: "Least Concern",
exhibit: false,
dominance: "None",
relationship_human: "Shy",
mating_system: "Polygynous"
}]
the my function does not seem to add the elements properly to the searchList I'd like to display as long as the query is not empty but I'm unable to find the issue here.
Part of fluterSearchResults function is the reason causing error.
You use the same list for searching, [searchList].
It always search in an empty list.
Try
List responseList = widget.res;
List<String> searchList = List<String>();
responseList.forEach((response) {
if (response.contains(query)) {
searchList.add(response);
}
setState(() {
items.clear();
items.addAll(searchList);
});
});
return;
I hope the problem will be solved.

Let user settle picking value from CupertinoPicker(onSelectedItemChanged ), after that it should send call to API

I am using CupertinoWidget for iOS users to scroll through List and check the price of a currency. But when scroll happens, onSelectedItemChanged sends callback to API for every value from the list. I read the document but unable to understand what to do. It pleasing if there is an example.
In document it's mentioned as CupertinoPicker > onSelectedItemChanged property
This can be called during scrolls and during ballistic flings. To get the value only when the scrolling settles, use a NotificationListener, listen for ScrollEndNotification and read its FixedExtentMetrics.
NotificationListener cupertinoPickerList() {
List<Text> textWidgetList = [];
for (String curreny in currenciesList) {
textWidgetList.add(
Text(
curreny,
style: TextStyle(
color: Colors.white,
),
),
);
}
return NotificationListener<ScrollNotification>(
onNotification: (scrollNotification) {
if (scrollNotification is ScrollEndNotification) {
return true;
} else {
return false;
}
},
child: CupertinoPicker(
itemExtent: 30,
scrollController: FixedExtentScrollController(initialItem: 19),
onSelectedItemChanged: (selectedIndex) {
selectedCurreny = currenciesList[selectedIndex];
updateUI(selectedCurreny);
print(selectedCurreny);
},
children: textWidgetList,
),
);
}
You can check if the metrics of the scrollNotification are of type FixedExtentMetrics. This type has the value itemIndex which you can use to determine which item is currently selected.
return NotificationListener<ScrollNotification>(
onNotification: (scrollNotification) {
if (scrollNotification is ScrollEndNotification &&
scrollNotification.metrics is FixedExtentMetrics) {
(scrollNotification.metrics as FixedExtentMetrics).itemIndex; // Index of the list
return true;
} else {
return false;
}
},
With the help of Juliantje15's code, here is a full solution:
final widget = NotificationListener<ScrollEndNotification>(
onNotification: (notification) {
if (notification.metrics is! FixedExtentMetrics) {
return false;
}
final index = (notification.metrics as FixedExtentMetrics).itemIndex;
// This would be your callback function. Could use items[index]
// or something if that's more appropriate of course.
onItemChanged(index);
// False allows the event to bubble up further
return false;
},
child: CupertinoPicker(
itemExtent: 32,
onSelectedItemChanged: null, // Attribute is marked required
children: [Text('item1'), Text('item2'), Text('etc')],
),
);
It seems quite sensible to want this, so I guess it's a bit strange that this isn't included as an (optional) default behavior. I guess you could turn the wrapper into a custom widget if it's needed more often.

TextField Widget with emoji flutter

How can I open keyboard type == emoji. Not number, not letter, just emoji. Without using emoji_picker package
To open the emoji container emoji_picker
Create A method emojiContainer
emojiContainer() {
return EmojiPicker(
bgColor: Colors.red,
indicatorColor: Colors.blue,
rows: 3,
columns: 7,
onEmojiSelected: (emoji, category) {
setState(() {
isWriting = true;
});
textFieldController.text = textFieldController.text + emoji.emoji;
},
recommendKeywords: ["face", "happy", "party", "sad"],
numRecommended: 50,
);
}
And use an onPressed
onPressed: () {
if (!showEmojiPicker) {
// keyboard is visible
hideKeyboard();
showEmojiContainer();
} else {
//keyboard is hidden
showKeyboard();
hideEmojiContainer();
}
},