how to filter data from stream builder in flutter - flutter

body: Observer<List<CompleteInventroyModel>>(
stream:call? completeInventoryManager.mainList:Stream.empty(),
onSuccess: (context, snapshot) {
List<CompleteInventroyModel> screendata =List.from(snapshot) ;
// List showlist=screendata[0].data.where((item) => item.areaId==1) as List;
//
if(filterData == true){
** showlist = screendata.map((e) => e).toList();
print("===========snapshot length============${snapshot[0].data.length}");
print("===========showlist[0].data.length============${showlist[0].data.length}");
print("===========screendata[0].data.length============${screendata[0].data.length}");
for (int i = 0; i < screendata[0].data.length; i++) {
print("==============i============${i}");
print('area_dv ${area_dv}');
// modeldata.Data obj = screendata[0].data[i];
if (screendata[0].data[i].area.name != area_dv) {
showlist[0].data.removeAt(i);
// showlist[0].data.add(screendata[0].data[i]);
//break;
// print("=================obj daata ${obj.area.name}");
}
}**
}
else if(filterData == false){
showlist = screendata.map((e) => e).toList();
}
I have tried both add and removeAt() method in remove add method also remove data from model original list and in add() method loop can't break ..any solution??

Related

The method 'add' can't be unconditionally invoked because the receiver can be 'null'

I'm trying to handle some data for a flutter application, however I am getting the following error on my code:
The method 'add' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').
Map<String, List<SourcefulListing>> sortedSkills = {};
QuerySnapshot listingSnapshot = await listingsRef.get();
List<SourcefulListing> listings = [];
for (int i = 0; i < listingSnapshot.docs.length; i++) {
listings.add(SourcefulListing.fromJson(
listingSnapshot.docs[i].data() as Map<String, dynamic>));
}
for (String skill in skills) {
for (SourcefulListing listing in listings) {
if (listing.selectedSkill == skill) {
if (sortedSkills[skill] == null || sortedSkills[skill] != []) {
sortedSkills[skill] = [listing];
} else {
sortedSkills[skill] = sortedSkills[skill].add(listing);
}
}
}
}
Basically I have a Map with Strings as key and List for the values. The for each loop should add the SourcefulListing object to the map, however there is an error on the .add method.
Any help would be much appreciated.
Try this,
Map<String, List<SourcefulListing>> sortedSkills = {};
QuerySnapshot listingSnapshot = await listingsRef.get();
List<SourcefulListing> listings = [];
for (int i = 0; i < listingSnapshot.docs.length; i++) {
listings.add(SourcefulListing.fromJson(
listingSnapshot.docs[i].data() as Map<String, dynamic>));
}
for (String skill in skills) {
for (SourcefulListing listing in listings) {
if (listing.selectedSkill == skill) {
if (sortedSkills[skill] == null || sortedSkills[skill] != []) {
sortedSkills[skill] = [listing];
} else {
sortedSkills[skill]?.add(listing); // changes made here
setState(() {}); // update ui
}
}
}
}
Null Safety : https://dart.dev/null-safety

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();
}
});
});

How to check for an list array that has more than 1 String

I have a array here and I want to check If in that array I have more that 1 string or not as describe in
code:
bool? checkEmpty1 = false;
StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance
.collection('groups')
.doc(groupId)
.snapshots(),
builder: (context, snapshot2) {
snapshot2.data?.data()?.forEach((key, value) {
if (key == 'members') {
checkEmpty1 = value == '';
}
});
//I want to do like If members is more than 1 show this If members == to 1 show this
return checkEmpty1!
? const Text('Has one members')
: const Text('Has more than one members')
picture:
// declare variable which will count the number of String in the list
int stringCount = 0;
if (checkEmpty1 != null) {
for (int i = 0; i < checkEmpty1.length; i++) {
if (checkEmpty1[i] is String) {
// increase the string count by 1
stringCount++;
}
//now you can check the stringCount count to determine the number of string in the list
if (stringCount > 1) {
//this will know that there are more than one String in the list,
return;
}
}
}

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

Fixed List is not updating with for loop - Flutter

I've a fixed list reservedGuest. After checking the condition in for loop I want to update the seats if the membership date has expired. The list is not updating. The code is as follows. PS. The List is filled through API on init().
class MyClubController extends GetxController {
List goldLane = List.filled(3, null, growable: false);
void _alterLanesOnContractEnds() {
for (var i in goldLane) {
print("\n\n I: $i");
if (i == null ||
DateTime.parse(i['contractEnds']).isBefore(
DateTime.now(),
)) {
i = null;
print('Can be removed');
} else {
print('Cannot be removed');
}
}
update();
}
}
A for-in loop will not allow you to reassign elements of the List. When you do:
for (var i in goldLane) {
// ...
i = null;
}
you are reassigning what the local i variable refers to, not mutating the goldLane List.
You instead can iterate with an index:
void _alterLanesOnContractEnds() {
for (var i = 0; i < goldLane.length; i += 1) {
var element = goldLane[i];
print("\n\n I: $element");
if (element == null ||
DateTime.parse(element['contractEnds']).isBefore(
DateTime.now(),
)) {
goldLane[i] = null;
print('Can be removed');
} else {
print('Cannot be removed');
}
}
update();
}
You can just create a new List where unqualified guests are nullified. For example,
void _alterLanesOnContractEnds() {
goldLane = goldLane.map(
(guest) => guest == null || DateTime.parse(guest['contractEnds']).isBefore(DateTime.now()) ? null: guest
).toList(growable: false);
update();
}
You should not and cannot modify a list while iterating with its iterator.
Elaborated by Jamesdlin,
Modifying the elements of a List while iterating is fine. Modifying
the length of the List while iterating is not, but that won't be a
problem for a non-growable List.
The bottom line is you should not mutate the size of the list while iterating.
I solved it by using
goldLane.forEach(
(element) {
print('\n\n ELEMENT: $element');
if (element == null ||
DateTime.parse(element['contractEnds']).isBefore(
DateTime.now(),
)) {
int ix = goldLane.indexWhere(
(element) => element != null
? DateTime.parse(element['contractEnds']).isBefore(
DateTime.now(),
)
: true,
);
goldLane[ix] = null;
} else {
print('Cannot be removed');
}
},
);
Yet I'll test the other answers. Thank You.