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

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

Related

how to filter data from stream builder in 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??

How can you reload data that is generated through Builder BlocConsumer?

I tried to write my own action Future using . clear() and re-generate it in the same place, but it didn't work.
For example, it first generates data for the month of the last image (August), selects May and it clears August data and generates for May.
To explain: I get data for several months or years, for example: August 2022, May 2022, December 2021, etc.
To make the code more optimized I want to generate first for the last incoming item, and then when I click on a certain month in the dropdown, deleting the old data to generate new data for the month and year he chose.
#override
Widget build(BuildContext context) {
final _provider = Provider.of<MapRepository>(context);
currentIndicator = _provider.fieldIndicator;
filterLayer = _provider.filterLayer;
selectedMonth = currentIndicator != null ? currentIndicator!.getMonth : "";
selectedYear = currentIndicator != null ? currentIndicator!.getYear : "";
String dateMonth =
currentIndicator != null ? "$selectedMonth $selectedYear" : "Загрузка";
_controller = FixedExtentScrollController(initialItem: 0);
return BlocConsumer(
bloc: indicatorBloc,
listener: (context, state) {
if (state is FetchedIndicatorsState) {
int lastPresent = 0;
Future.delayed(Duration(seconds: 1)).then((value) {
for (int i = 0; i < indicators.length; i++) {
if (indicators.reversed.toList()[i].isPresent) {
lastPresent = i;
}
dates.add(indicators[i].getDateTime);
}
for (var date in dates) {
String shortMonth = DateFormat("MMM", "ru").format(date);
String year = DateFormat("yy", "ru").format(date);
String month =
DateFormat("MMMM", "ru").format(date).toCapitalized();
indicatorDates['$shortMonth$year'] = '$month ${date.year}';
}
selectIndicator(indicators.reversed.toList()[lastPresent]);
});
}
},
builder: (context, state) {
if (state is FetchedIndicatorsState) {
indicators = state.indicators;
for (int i = 0; i < indicators.length; i++) {
if (indicators[i].getMonth == selectedMonth &&
indicators[i].getYear == selectedYear) {
childrenIndicators.add(buildIndicator(
indicators[i], indicators[(i - 1 < 0) ? 0 : (i - 1)], i));
}
}
return buildBody(context, dateMonth, childrenIndicators);
}
return Container();
},
);
}
OnTap actions:
onTap: () {
_refreshData();
setState(() {
selectedYear = entry.value.substring(entry.value.length - 5);
selectedMonth = entry.value.substring(0, entry.value.length - 5);
});
Navigator.pop(context);
},
My action:
Future _refreshData() async {
await Future.delayed(Duration(seconds: 3));
childrenIndicators.clear();
for (int i = 0; i < indicators.length; i++) {
if (indicators[i].getMonth == selectedMonth &&
indicators[i].getYear == selectedYear) {
childrenIndicators.add(buildIndicator(
indicators[i], indicators[(i - 1 < 0) ? 0 : (i - 1)], i));
}
}
setState(() {});
}

Expected a value of type 'string' but got one of type 'int' - Flutter

I have a function that returns a String, but when I call this function, the app screen goes red and I get this error: Expected a value of type 'string' but got one of type 'int'.
Here is my function that returns a String:
checkProportion(String predominantGamete, String resultado) {
var countBrown = 0;
var countBlack = 0;
var countWhite = 0;
var proportionCamundongo =
'Proporção: ${countBrown}:${countBlack}:${countWhite}';
if (predominantGamete == 'recessiva_aa' &&
resultado.contains('A') &&
resultado.contains('P')) {
return countBrown += 1;
} else if (predominantGamete == 'recessiva_aa' &&
resultado.contains('A') &&
resultado.contains('pp')) {
return countBlack += 1;
} else if (predominantGamete == 'recessiva_aa' &&
resultado.contains('aa')) {
return countWhite += 1;
}
return proportionCamundongo;
}
Here is how I call the function:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
title: Text(
checkProportion(widget.predominant, widget.result),
),
),
How to solve this error?
Here is an image that shows the colors of each result:
The issue here is that you are returning early, not breaking the if statement, when you do something like return countBrown += 1;;
Try incrementing the counters, then using string interpolation to display the value:
String checkProportion(String predominantGamete, String resultado) {
int countBrown = 0;
int countBlack = 0;
int countWhite = 0;
if (predominantGamete == 'recessiva_aa' &&
resultado.contains('A') &&
resultado.contains('P')) {
countBrown += 1;
} else if (predominantGamete == 'recessiva_aa' &&
resultado.contains('A') &&
resultado.contains('pp')) {
countBlack += 1;
} else if (predominantGamete == 'recessiva_aa' &&
resultado.contains('aa')) {
countWhite += 1;
}
return 'Proporção: ${countBrown}:${countBlack}:${countWhite}';
}
I'd also recommend specifing the return type of the function (String), using the correct types for counters (int). That will help your compiler catch the issues as well.
It isn't my best work, and there is probably a better way to check for if a string contains all occurrence of multiple substrings, but here you go:
bool isColorContained(String resultado, Set<String> requirements) {
for(String requirement in requirements) {
if (!resultado.contains(requirement)) {
return false;
}
}
return true;
}
 
String checkProportion(String predominantGamete, String resultado) {
Map<ColorType, Set<String>> colorType = {
ColorType.brown: {'A', 'P'},
ColorType.black: {'A', 'pp'},
ColorType.white: {'aa'},
};
Map<ColorType, int> colorTypeCount = {
ColorType.brown: 0,
ColorType.black: 0,
ColorType.white: 0,
};
for(MapEntry<ColorType, Set<String>> entry in colorType.entries ) {
if(predominantGamete != 'recessiva_aa') continue;
bool contained = isColorContained(resultado, entry.value);
if(contained) {
int count = colorTypeCount[entry.key] ?? 0;
colorTypeCount[entry.key] = count + 1;
}
}
return 'Proporção: ${colorTypeCount[ColorType.brown]}:${colorTypeCount[ColorType.black]}:${colorTypeCount[ColorType.white]}';
}
 
Also, declare the ColorType enum:
enum ColorType {
brown, black, white
}
This will scale with as many colors and requirements you have, by adding to the ColorType enum, the colorType map, and the colorTypeCount map.

Flutter search from model provider

After a few days it didn't work, I combined the data on the model initially
example: Samsung has a lot of data and I have combined it into an array, I want to ask how to make a search based on the brand name of the model?
#override
Widget build(BuildContext context) {
remoteModelId.clear();
isLoading = true;
final products = Provider.of<List<Brands>>(context);
return Scaffold(
...
body: products != null
? ListView.separated(
itemCount: products.length,
itemBuilder: (context, index) {
var lol = [];
var idModel = [];
var sublist = [].join();
var countList =[];
//var allList =[];
//var subLol = lol.indexOf(lol);
for(var ok in products){
lol.add(ok.brandName);
idModel.add(ok.ids);
countList.add(lol);
if(lol.contains(lol)){
sublist.compareTo(lol[index]);
break;
}
}
distinctIds = lol.toSet().toList();
hasilakhir = Set.of(distinctIds).toList();
newDataList = List.from(distinctIds);
templist.add(hasilakhir);
final myMap = Map();
lol.forEach((element) {
if(!myMap.containsKey(element)){
myMap[element] = 1;
return false;
}else{
myMap[element] += 1;
return false;
}
});
//newDataList = newDataList.map((brand)=>brand.toLowerCase()).toList();
return ListTile(
title: Text(hasilakhir[index]),
Thanks
I am not sure what you need, but here is some example code:
// Get products with a specific brandName
print(
'Number of Samsung=${products.where((p) => p.brandName == 'Samsung').length}');
// Count products by brandName - like your code
final map = Map();
products.forEach((product) {
if (!map.containsKey(product.brandName)) {
map[product.brandName] = 1;
} else {
map[product.brandName] += 1;
}
});
print('map=$map');
// Group products by brandName, with the count and list of ids
final map2 = Map();
products.forEach((product) {
if (!map2.containsKey(product.brandName)) {
map2[product.brandName] = {
'count': 1,
'ids': [product.ids]
};
} else {
var current = map2[product.brandName];
current['count']++;
current['ids'].add(product.ids);
}
});
print('map2=$map2');
The output with my test data is:
Number of Samsung=3
map={Samsung: 3, Apple: 3}
map2={Samsung: {count: 3, ids: [S1, S2, S3]}, Apple: {count: 3, ids: [iPhone1, iPhone2, iPhone3]}}
I do not know if it is helpful, but I have annotated some of your code below:
// Get list of distinct brandNames
var distinctIds = lol.toSet().toList();
// Get list of distinct brandNames - same as distinctIds
var hasilakhir = Set.of(distinctIds).toList();
// Copy list distinctIds
var newDataList = List.from(distinctIds);
List templist = [];
// Make a list with one element which is the list of brandNames
templist.add(hasilakhir);

Dart : Convert From Iterable<ActivityModel> To ActivityModel

I have model Like This :
Model
class ActivityModel {
String idActivity;
String titleActivity;
String dateTimeActivity;
int isDoneActivity;
int codeIconActivity;
String informationActivity;
String createdDateActivity;
ActivityModel({
this.idActivity,
this.titleActivity,
this.dateTimeActivity,
this.isDoneActivity,
this.codeIconActivity,
this.informationActivity,
this.createdDateActivity,
});
ActivityModel.fromSqflite(Map<String, dynamic> map)
: idActivity = map['id_activity'],
titleActivity = map['title_activity'],
dateTimeActivity = map['datetime_activity'],
isDoneActivity = map['is_done_activity'],
codeIconActivity = map['code_icon_activity'],
informationActivity = map['information_activity'],
createdDateActivity = map['created_date'];
Map<String, dynamic> toMapForSqflite() {
return {
'id_activity': this.idActivity,
'title_activity': this.titleActivity,
'datetime_activity': this.dateTimeActivity,
'is_done_activity': this.isDoneActivity,
'code_icon_activity': this.codeIconActivity,
'information_activity': this.informationActivity,
'created_date': this.createdDateActivity,
};
}
I want get data where dateTimeActivity is before than date now, then i update isDoneActivity = 1 with this code :
Source code
final passedDateItem = _selectedActivityItem.where((element) {
DateTime convertStringToDateTime =
DateTime.parse(element.dateTimeActivity);
return convertStringToDateTime.isBefore(DateTime.now());
});
if (passedDateItem != null) {
print('Not Null');
} else {
print('Nulledd');
return null;
}
The problem is , passedDateItem return Iterable[ActivityModel] , it's possible to convert it to ActivityModel? So i can easly update like this ?
if (passedDateItem != null) {
passedDateItem.isDoneActivity = 1; <<<
// return passedDateItem.map((e) => e.isDoneActivity = 1);
// final testtt= passedDateItem.
print('Not Null');
} else {
print('Nulledd');
return null;
}
Iterate through passedDateItem
for (var activityModel in passedDateItem) {
//..conditions
activityModel.isDoneActivity = 1;
}
If you are only interested in the first/last element of passedDateItem
use
passedDateItem.first.isDoneActivity == 1
or
passedDateItem.last.isDoneActivity == 1
make sure passedDateItem is not empty in that case.