flutter search in search - flutter

This is the onsearch function that searches for all custnum addresses.
onSearch(String text) async {
print(text);
List<Item> itemII = items;
if (text.isNotEmpty) {
List<Item> itemList = [];
for (var item in itemII) {
if (item.custnum == text.toLowerCase().toUpperCase()) {
itemList.add(item);
}
}
setState(() {
searchText = text;
searchitems.clear();
searchitems.addAll(itemList);
MainPage.searchItemMainPage.addAll(itemList);
if (searchitems.isNotEmpty) {
print({MainPage.searchItemMainPage[0].address});
searchitems[0].address!.sort((a, b) {
if (a.for_bill == 'Y' && b.for_bill == 'N') {
return -1;
} else if (a.for_bill == 'N' && b.for_bill == 'Y') {
return 1;
} else if (a.for_ship == 'Y' && b.for_ship == 'N') {
return -1;
} else if (a.for_ship == 'N' && b.for_ship == 'Y') {
return 1;
} else if (a.for_contact == 'Y' && b.for_contact == 'N') {
return -1;
} else if (a.for_contact == 'N' && b.for_contact == 'Y') {
return 1;
} else {
return 0;
}
});
}
});
} else {
setState(() {
searchCus.clear();
searchitems.clear();
MainPage.searchItemMainPage.clear();
// searchitems.addAll(items);
print('searchitems : $searchitems');
});
}
}
This is the onsearchaddr function, it finds the address in searchitems after the search. By typing the name of the field addr, then the address will be displayed.
onSearchAddr(String text) {
List<Item> result = searchitems;
if (text.isNotEmpty) {
List<Item> itemList = [];
for (var item in result) {
item.address = item.address!
.where((element) =>
element.addr1!.toUpperCase().toLowerCase().contains(text))
.toList();
itemList.add(item);
}
setState(() {
searchitems.clear();
searchitems.addAll(itemList);
print('itemList : ${itemList}');
});
} else {
setState(() {
searchitems.clear();
searchitems.addAll(MainPage.searchItemMainPage);
print(
'SearchitemsMainPage : ${MainPage.searchItemMainPage[0].address}');
});
}
}
Could you please write some code to modify onsearchaddr, it can search as typed but when it clears text it doesn't show information of searchitems as before but it shows information of last typed message.
It's like the previous backup wasn't provided.

Related

The function finds only one element, even if there is more than one

The function below finds only one item in the list, even if there are multiple items, how do I fix this function to find all items?
List newList = [];
if (value.isNotEmpty) {
for (var element in pressures) {
if (element.pressure.contains(value) ||
element.date.toString().contains(value)) {
newList.clear();
newList.add(element);
}
}
items.value = newList;
} else {
items.value = pressures;
}
You are clearing the list on loop
if (value.isNotEmpty) {
newList.clear(); // you can clear it on top of the loop
for (var element in pressures) {
if (element.pressure.contains(value) ||
element.date.toString().contains(value)) {
// newList.clear(); //remove this
newList.add(element);
}
}
items.value = newList;
} else {
items.value = pressures;
}

In Dart Flutter, if else conditions causing problems

In Dart Flutter if else conditions causing problems.
In this method with if else conditions the forEach loop is not working properly
as it does not allowing the print statement to print each key and value in the map.
Data for map comes from the firestore database
But
when I remove if else conditions , then it is working properly
Please help.
CODE
Future<List<ReviewModel>> getCakeReview(String cakeId) async {
CollectionReference snap = types.doc(cakeId).collection('Reviews');
List<ReviewModel> list = [];
ReviewModel model = ReviewModel("", "", 0, "");
String userName = "";
String userDP = "";
String review = "";
int rating = 0;
await snap.get().then((value) {
for (var result in value.docs) {
Map<String, dynamic> map = result.data() as Map<String, dynamic>;
print(map);
int i = 0;
map.forEach((key, value) {
print(key.toString() + ":" + value.toString());
print(i++);
if (key.toString() == 'userName') {
userName = value.toString();
} else if (key.toString() == 'userDP') {
userDP = value.toString();
} else if (key.toString() == 'rating') {
rating = value;
} else {
review = value.toString();
}
});
model = ReviewModel(userName, userDP, rating, review);
list.add(model);
}
});
print("FS");
return list;
}
Output Image link
replace
map.forEach((key, value) {
print(key.toString() + ":" + value.toString());
print(i++);
if (key.toString() == 'userName') {
userName = value.toString();
} else if (key.toString() == 'userDP') {
userDP = value.toString();
} else if (key.toString() == 'rating') {
rating = value;
} else {
review = value.toString();
}
});
with
userName = map['userName'];
userDP = map['userDP'];
rating = map['rating'];
review = map['review'];
to eliminate the "for-switch" anti-pattern.
Now I got what was the problem,
I try to store the value(which is not integer when returned from firebase I think) into the rating variable which is an integer type
so what I did is,
parsed the value to integer and it worked fine.
Code
map.forEach((key, value) {
print(key.toString() + ":" + value.toString());
print(i++);
if (key.toString() == 'userName') {
userName = value.toString();
} else if (key.toString() == 'userDP') {
userDP = value.toString();
} else if (key.toString() == 'rating') {
rating =int.parse(value);
} else {
review = value.toString();
}
});

XMLHTTPRequest error but only when added to main project

so I have this code:
import 'dart:convert';
import 'package:http/http.dart' as http;
List getMenuDay(String day, List canteenMenu) {
if (day == "tuesday") {
return canteenMenu[0];
}
else if (day == "wednesday") {
return canteenMenu[1];
}
else if (day == "thursday") {
return canteenMenu[2];
}
else if (day == "friday") {
return canteenMenu[3];
}
else if (day == "saturday") {
return canteenMenu[4];
}
else if (day == "sunday") {
return canteenMenu[5];
}
else {
return [];
}
}
String getDayPlate(String day, String plate, List canteenMenu) {
List dayMenu = getMenuDay(day, canteenMenu);
if (plate == "sopa") {
return dayMenu[0];
}
else if (plate == "carne") {
return dayMenu[1];
}
else if (plate == "peixe") {
return dayMenu[2];
}
else if (plate == "dieta") {
return dayMenu[3];
}
else if (plate == "vegetariano") {
return dayMenu[4];
}
return "";
}
void main() async {
List list = [];
List helper = [];
const canteenUrl = 'https://sigarra.up.pt/feup/pt/mob_eme_geral.cantinas';
var response = await http.get(Uri.parse(canteenUrl));
if (response.statusCode == 200) {
var data = json.decode(response.body);
for (int i = 0; i < 4; i++) { // loop through different days
for (int j = 0; j < 5; j++) { // loop through different types of food
var parkInfo = data[3]["ementas"][i]["pratos"][j]["descricao"];
helper.add(parkInfo);
//print(parkInfo);
}
list.add(helper);
helper = [];
//print("--------------");
}
/*
for (int i = 0; i < list.length; i++) {
print(list[i]);
}
*/
print(getDayPlate("thursday", "carne", list));
} else {
throw Exception('Failed to read $canteenUrl');
}
}
and when I just create a new project, type it into the main.dart file and run it, it works fine. But when I add it to make whole project, including other files (making the necessary changed like changing the name of the function, etc), it gives me the XMLHTTPRequest error. What could be causing that? The way I'm calling it withing the main project is as follows:
ElevatedButton(
style: style,
onPressed: () {
CanteenInfo canteen = CanteenInfo("tuesday","sopa");
print(canteen.getDayPlate());
},
child: const Text('ShowLen (WIP)'),
Thanks for any help you could give!
Edit 1: I do get a warning when running just the code,
lib/main.dart: Warning: Interpreting this as package URI, 'package:new_test/main.dart'.

PageView and AnimateToPage - How to dynamically animate to Page to the scrolled position in Flutter

I have cards which are getting scrolled successfully through a Page Controller and animate to Page. Now my issue is that even though it is iterated correctly, if I scroll myself to the right or left it leaves me back at the starting position aka _currentPage=0. I want the system to know dynamically that if 0 is the starting position and I have scrolled manually to the 3rd position, I want it to go to the 4th position and not start at the 0th position again. Similarly, if I have scrolled backwards to the 6th position I want it to go forward from where I scrolled not back to 0. Is there a way to achieve this dynamically?
Please refer to the Timer.periodic code I tried adding a gesture Detector but that wouldn't work the program would not scroll at all.
Timer _mytimer;
bool _mytimerz = false;
int _timerspeed = 15;
int _currentPage = 0;
bool _speedtime = false;
PageController _pageController = PageController(
initialPage: 0,
);
// timerforthisThis() {
void initState() {
super.initState();
tests = [
widget.label00,
widget.label0,
widget.label1,
widget.label2,
widget.label3,
widget.label4,
widget.label5,
widget.label6,
widget.label7,
widget.label8,
widget.label9,
widget.label10,
widget.label11,
widget.label12,
widget.label13,
widget.label14,
widget.label15,
widget.label16,
widget.label17,
widget.label18,
widget.label19,
widget.label20,
widget.label21,
widget.label22,
widget.label23,
widget.label24,
widget.label25,
widget.label26,
widget.label27,
widget.label28,
widget.label29,
widget.label30,
widget.label31,
widget.label32,
widget.label33,
widget.label34,
widget.label35,
widget.label36,
widget.label37,
];
results = [];
for (int i = 0; i < tests.length; i++) {
if (widget.label00 != '') {
results.add(widget.label00);
}
if (widget.label0 != '') {
results.add(widget.label0);
}
if (widget.label1 != '') {
results.add(widget.label1);
}
if (widget.label2 != '') {
results.add(widget.label2);
}
if (widget.label3 != '') {
results.add(widget.label3);
}
if (widget.label4 != '') {
results.add(widget.label4);
}
if (widget.label5 != '') {
results.add(widget.label5);
}
if (widget.label6 != '') {
results.add(widget.label6);
}
if (widget.label7 != '') {
results.add(widget.label7);
}
if (widget.label8 != '') {
results.add(widget.label8);
}
if (widget.label9 != '') {
results.add(widget.label9);
}
if (widget.label10 != '') {
results.add(widget.label10);
}
if (widget.label11 != '') {
results.add(widget.label11);
}
if (widget.label12 != '') {
results.add(widget.label12);
}
if (widget.label13 != '') {
results.add(widget.label13);
}
if (widget.label14 != '') {
results.add(widget.label14);
}
if (widget.label15 != '') {
results.add(widget.label15);
}
if (widget.label16 != '') {
results.add(widget.label16);
}
if (widget.label17 != '') {
results.add(widget.label17);
}
if (widget.label18 != '') {
results.add(widget.label18);
}
if (widget.label19 != '') {
results.add(widget.label19);
}
if (widget.label20 != '') {
results.add(widget.label20);
}
if (widget.label21 != '') {
results.add(widget.label21);
}
if (widget.label22 != '') {
results.add(widget.label22);
}
if (widget.label23 != '') {
results.add(widget.label23);
}
if (widget.label24 != '') {
results.add(widget.label24);
}
if (widget.label25 != '') {
results.add(widget.label25);
}
if (widget.label26 != '') {
results.add(widget.label26);
}
if (widget.label27 != '') {
results.add(widget.label27);
}
if (widget.label28 != '') {
results.add(widget.label28);
}
if (widget.label29 != '') {
results.add(widget.label29);
}
if (widget.label30 != '') {
results.add(widget.label30);
}
if (widget.label31 != '') {
results.add(widget.label31);
}
if (widget.label32 != '') {
results.add(widget.label32);
}
if (widget.label33 != '') {
results.add(widget.label33);
}
if (widget.label34 != '') {
results.add(widget.label34);
}
if (widget.label35 != '') {
results.add(widget.label35);
}
if (widget.label36 != '') {
results.add(widget.label36);
}
if (widget.label37 != '') {
results.add(widget.label37);
}
}
Timer.periodic(Duration(seconds: 5), (Timer timer) {
// if (_mytimerz = true) {
// timer.cancel();
// }
// if (_speedtime = false) {
// Timer.periodic(Duration(seconds: 2), (timer) {});
if (_currentPage < results.length) {
_currentPage++;
// _currentPage++;
}
// _speedtime = true;
// timer.cancel();
// } else {
// GestureDetector(onPanUpdate: (details) {
// if (details.delta.dx > 0 || details.delta.dx < 0) {
// print("right");
// }
// });
// _currentPage = _currentPage;
// // 0
// }
_pageController
.
// animateTo(
// _pageController.,
// duration: , curve: curve)
animateToPage(
// results.length,
_currentPage = _currentPage,
duration:
// _speedtime
// ?
// Duration(milliseconds: 0),
// :
Duration(milliseconds: 350),
curve: Curves.easeIn,
);
}
// );
// );
// }
);
}
First, have a variable to feed the page view index like pageViewIndex
Initialise the PageController in the initState method with the pageViewIndex
Then in the PageView's onPageChanged method do setState for the pageViewIndex and animate the PageController to the (new) pageViewIndex
Hope that should do.
Comment down if any other help is needed.

Unhandled Exception: Unhandled error 'package:bloc/src/transition.dart': Failed assertion: line 27 pos 16: 'nextState != null': is not true

I am getting this error while updating a value in state . please suggest me how to resolve it. what is best way to update current state while working with BLOC in flutter. My BLOC class code added. This Error Occurs onItemClick Event.
onItemClicked: (e) async* {
try {
yield walmartState;
List<CommonDataObj> dataList =
walmartItemChanged(e.index, e.walmartList);
yield state.copyWith(walmartList: some(right(dataList)));
LinkedHashMap<String, RequestData> reqMap = state.requestDataMap;
dataList.forEach((element) {
if (element.isSelected) {
RequestData data = RequestData(element.intStoreId, element.intId);
if (reqMap.containsKey(e.key)) {
reqMap.update(e.key, (value) => data);
} else {
reqMap.putIfAbsent(e.key, () => data);
}
} else {
if (reqMap.containsKey(e.key)) {
var value = reqMap[e.key];
if (value.int_product_id == element.intId &&
value.int_store_id == element.intStoreId) {
reqMap.remove(e.key);
}
}
}
});
yield state.copyWith(requestDataMap: reqMap);
yield state.copyWith(requestDataMap: reqMap);
print('State request Data Map : $reqMap');
} catch (e) {
print(e);
}
try {
bool selected = false;
e.currentDataMap.forEach((key, value) {
for (var item in value) {
if (item.isSelected) {
selected = true;
break;
}
}
});
int curQuantity = state.currentQuantity;
if (curQuantity == 0) {
curQuantity = curQuantity + 1;
} else if (curQuantity > 0 && !selected) {
curQuantity = 0;
}
var newState = state.copyWith(currentQuantity: curQuantity);
yield newState;
} catch (e) {
print(e);
}
}