how to create an exception inside a flutter for loop - flutter

I need the items inside a for to have an action with the exception of the last one, which will have a different action
an example that DOESN'T WORK:
for (var i = 0; i < 10; i++) {
print('1 - 9');
if (i.last) {
print('last item');
}
}

You can put method in the condition part of the for loop. Here is such example:
void main() {
const limit = 10;
for(int i =0 ;
() {
if(i < limit && i < limit-1) {
doActionA(i);
return true;
}
else if(i < limit){
doActionB(i);
return true;
}
return false;
}()
; i++);
}
void doActionA(int i){
print('Not last $i');
}
void doActionB(int i) {
print('last $i');
}
output
Not last 0
Not last 1
Not last 2
Not last 3
Not last 4
Not last 5
Not last 6
Not last 7
Not last 8
last 9

Try this:
for (var i = 0; i < 10; i++) {
print('0 - 8');
if (i == 9) {
print('last item');
}
}

you can try this
for (var i = 0; i < 10; i++) {
print('1 - 9');
if (i==9) {
print('last item');
throw Exception("Your message");
}
}

This is also possible, you can just paste the snippet in DartPad and play with it
void main() {
try {
for (var i = 0; i < 10; i++) {
if (i == 3) {
print('item $i');
throw 'customError';
} else {
print('item $i');
}
}
} catch (e) {
if (e == 'customError') {
print('You caught your custom error \n $e');
} else {
print('You caught some other error');
}
}
}
Hope that will help

Related

flutter search in search

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.

Listen to a new value of a bloc and generate a list of listened items

I have this StreamSubscription field called followSubscribtion. It listens if there is a new follower and then calls populateFollower to load follower profile.
followsSubscription =
getBloc(context).followsHandler.stream.listen((value) async {
if (value.status == Status.success) {
await populateFollows();
}
});
});
populateFollows() async{
if (getBloc(context).followsModel.length > 0) {
for (var i = 0; i < getBloc(context).followsModel.length; i++) {
getBloc(context).loadFollowsProfile(getBloc(context).followsModel[i].userId);
break;
}
}
}
This works fine, But I want each profile that will be loaded to be added to a list, How do I do that?
loadFollowsProfile method
loadFollowsProfile(int id , List<UserProfileModel> profileList) {
getFollowsProfileHandler.addNetworkTransformerStream(
Network.getInstance().getUserProfile(id), (_) {
userProfileModelBloc = UserProfileModel.fromJson(_);
profileList.add(userProfileModelBloc);
return userProfileModelBloc;
});
}
You can do this by setting up loadFollowsProfile() to return a UserProfileModel, adding that to a list in the for loop of populateFollows(), and then returning that list from populateFollows().
List<ProfileObject> populateFollows() async{
List<ProfileObject> profileList = [];
if (getBloc(context).followsModel.length > 0) {
for (var i = 0; i < getBloc(context).followsModel.length; i++){
profileList.add(getBloc(context).loadFollowsProfile(
getBloc(context).followsModel[i].userId
));
break;
}
}
return profileList;
}
followsSubscription =
getBloc(context).followsHandler.stream.listen((value) async {
if (value.status == Status.success) {
profileList = await populateFollows();
}
});
});

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'.

In Flutter and if the number after decimal point is equal 0 convert the number to int

This is a function if the endValueFixed is equal for example 12.0 I want to print the number without zero so I want it to be 12.
void calculateIncrease() {
setState(() {
primerResult = (startingValue * percentage) / 100;
endValue = startingValue + primerResult;
endValueFixe`enter code here`d = roundDouble(endValue, 2);
});
}
This may be an overkill but it works exactly as you wish:
void main() {
// This is your double value
final end = 98.04;
String intPart = "";
String doublePart = "";
int j = 0;
for (int i = 0; i < end.toString().length; i++) {
if (end.toString()[i] != '.') {
intPart += end.toString()[i];
} else {
j = i + 1;
break;
}
}
for (int l = j; l < end.toString().length; l++) {
doublePart += end.toString()[l];
}
if (doublePart[0] == "0" && doublePart[1] != "0") {
print(end);
} else {
print(end.toString());
}
}
You may use this code as a function and send whatever value to end.
if (endValueFixed==12) {
print('${endValueFixed.toInt()}');
}
conditionally cast it to an int and print it then :)

Using the below script i am working on Pagination using Protractor script where is am seeing "summaryPage" is not defined

this.getPaginationsize = element.all(by.repeater('page in groupArray track by $index'));
summaryPage.getPaginationsize.count().then(function (pagination) {
if (pagination > 0) {
for (var i = 0; i < pagination; i++) {
summaryPage.getPaginationsize.get(i).click();
}
} else {
console.log('Pagination not exists');
}
});
this.getPaginationsize = element.all(by.repeater('page in groupArray track by $index'));
this.getPaginationsize.count().then(function (pagination) {
if (pagination > 0) {
for (var i = 0; i < pagination; i++) {
summaryPage.getPaginationsize.get(i).click();
}
} else {
console.log('Pagination not exists');
}
you should change it to this as you are referring to the same module you are present in