Flutter search from model provider - flutter

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

Related

how to update a collection if you already called it MongoDB Mongoos

Ok so I have a problem in which I use a collection to gather some ratings data and work with it, by the time I finish the rating update process, I have new ratings that I would like to update the collection with. However I can't call update because I get the error "Cannot overwrite model once compiled." I understand that I already called once the model to work with the data and that's why I get the error. is there any way I can update the collection? Or I will just have to workaround by creating a new collection with the latest rating, and then matching the latest ratings collection with the one I use to work with the data.
This is my code
let calculateRating = async () => {
const getData = await matchesCollection().find().lean();
const playerCollection = await playersCollection();
const getDataPlayer = await playerCollection.find().lean();
let gamesCounting = [];
getDataPlayer.forEach((player) => {
player.makePlayer = ranking.makePlayer(1500);
});
for (let i = 0; i < getData.length; i++) {
const resultA = getDataPlayer.findIndex(({ userId }, index) => {
if (userId === getData[i].userA) {
return index;
}
});
const resultB = getDataPlayer.findIndex(
({ userId }) => userId === getData[i].userB
);
const winner = getData[i].winner;
if (getDataPlayer[resultA] === undefined) {
continue;
} else if (getDataPlayer[resultB] === undefined) {
continue;
}
gamesCounting.push([
getDataPlayer[resultA].makePlayer,
getDataPlayer[resultB].makePlayer,
winner,
]);
}
ranking.updateRatings(gamesCounting);
let ratingsUpdate = [];
getDataPlayer.forEach((item) => {
let newRating = item.makePlayer.getRating();
let newDeviation = item.makePlayer.getRd();
let newVolatility = item.makePlayer.getVol();
item.rating = newRating;
item.rd = newDeviation;
item.vol = newVolatility;
ratingsUpdate.push(item);
});
};
I try the work around with creating the new collection

RiverPod Maintaining selected item of list

I am new to riverpod and trying to figure out a state management issue.
I have one list, and two independent states which need access to the list. The states also need to select an element of the list and know what its index is. The list can totally change (add or remove elements) and the states need to determine if their selected element is still in the list and update the index accordingly (to 0 if it is not found)
Here is an example with Riverpod in pure dart:
import 'package:riverpod/riverpod.dart';
void main(List<String> arguments) {
final container = ProviderContainer();
List<String> names = ["Jack", "Adam", "Sally"];
container.read(nameListProvider.notifier).setNames(names);
//selectedName1 = "Adam"
//selectedIndex1 = 1
//selectedName2 = "Sally"
//selectedIndex2 = 2
names.remove('Adam');
container.read(nameListProvider.notifier).setNames(names);
// print(selectedName1) = "Jack" // set to 0 because selection was removed
// print(selectedIndex1) = 0
// print(selectedName2) = "Sally"
// print(selectedIndex2) = 1 // decrement to match Sally's new list index
}
final nameListProvider =
StateNotifierProvider<NameListNotifier, List<String>>((ref) {
return NameListNotifier();
});
class NameListNotifier extends StateNotifier<List<String>> {
NameListNotifier() : super([]);
setNames(List<String> names) {
state = names;
}
}
But I need the selected Name and Index to be Providers
Update: Here is my more elegant solution:
import 'package:riverpod/riverpod.dart';
void main(List<String> arguments) {
final container = ProviderContainer();
List<String> names = ["Jack", "Adam", "Sally"];
print(container.read(nameListProvider));
container.read(nameListProvider.notifier).setNames(names);
var first = container.read(selectionProvider(1).notifier);
first.setName(1);
print(container.read(selectionProvider(1)).name);
var second = container.read(selectionProvider(2).notifier);
second.setName(2);
print(container.read(selectionProvider(2)).name);
names.remove('Adam');
List<String> newNames = List.from(names);
container.read(nameListProvider.notifier).setNames(newNames);
print(container.read(selectionProvider(1)).name);
print(container.read(selectionProvider(1)).index);
print(container.read(selectionProvider(2)).name);
print(container.read(selectionProvider(2)).index);
print(container.read(nameListProvider));
}
final selectionProvider =
StateNotifierProvider.family<SelectionNotifier, Selection, int>(
(ref, page) {
return SelectionNotifier(ref.read);
});
class SelectionNotifier extends StateNotifier<Selection> {
Reader _read;
SelectionNotifier(this._read) : super(Selection());
update() {
final String? selectedName = state.name;
final List<String> names = _read(nameListProvider);
if (names == []) {
state = Selection();
return null;
}
if (selectedName == null) {
state = Selection(name: names[0], index: 0);
return;
}
int i = names.indexOf(selectedName);
if (i == -1) {
state = Selection(name: names[0], index: 0);
return;
}
state = Selection(name: selectedName, index: i);
return;
}
setName(int index) {
final List<String> names = _read(nameListProvider);
state = Selection(name: names[index], index: index);
}
}
final nameListProvider =
StateNotifierProvider<NameListNotifier, List<String>>((ref) {
return NameListNotifier(ref.read);
});
class NameListNotifier extends StateNotifier<List<String>> {
Reader _read;
NameListNotifier(this._read) : super([]);
setNames(List<String> names) {
state = names;
_read(selectionProvider(0).notifier).update();
_read(selectionProvider(1).notifier).update();
}
}
class Selection {
final String? name;
final int? index;
Selection({this.name, this.index});
}

Flutter - Function - Return Array

I've build an List with 44 places:
List<String> departmentdes = new List(44);
after that I've called a function:
postDepartment();
The function is an api call:
postDepartment() async {
final response = await http.get('url');
final jsonresponse = json.decode(response.body);
List<Department> departments = [];
for(var d in jsonresponse) {
Department department = Department(
fid: d["fid"].toString(),
);
departments.add(department);
}
int index = departments.length -1;
for(int i = 0; i<=index; i++) {
departmentdes[i] = departments[i].fid;
}
return departmentdes;
}
After the postDepartment(); I want to print the departmentdes but it always returns null. Why?
i < index
You're already defining index to be length -1
Just a little logic error.
Change your postDepartment to this and see if it helps:
Future<void> postDepartment() async {
final response = await http.get('url');
final jsonresponse = json.decode(response.body);
List<Department> departments = [];
for(var d in jsonresponse) {
Department department = Department(
fid: d["fid"].toString(),
);
departments.add(department);
}
int index = departments.length -1;
for(int i = 0; i<=index; i++) {
departmentdes[i] = departments[i].fid;
}
return departmentdes;
}
Also check if your departments is not null.

Sort out dates for flutter check box/ Date scheduler

I have a service which returns a list of dates, which the user can opt for a future payment.
In the UI, there are three drop down boxes, one each for year, month and date.
Now when the user selects a particular year, then the months shown in the next drop down should only contain months corresponding to that particular selected year and similarly when the month is selected only the corresponding dates to that particular selected month should be shown.
The service response is something like below :
[
{
"availableDate":"03/13/2020"
},
{
"availableDate":"04/14/2020"
},
{
"availableDate":"01/15/2020"
},
{
"availableDate":"01/16/2020"
},
{
"availableDate":"02/17/2020"
},
{
"availableDate":"02/18/2020"
},
{
"availableDate":"02/22/2021"
}
]
I was able to split out the dates,months and years and when I tried to change values using onChange, didn't get the desired result. Could some one please help me with the logic or maybe give me a link to get started?
I have found out a solution.
First initialize the variables :
List _serviceData = [];
List _yearList = [];
List _monthList = [];
List _dateList = [];
List<SchedulerYear> _yearData = new List<SchedulerYear>();
List<SchedulerMonth> _monthData = new List<SchedulerMonth>();
List<SchedulerDate> _dateData = new List<SchedulerDate>();
var yearData = [];
var monthData = [];
var _loadData, _year, _month, _date;
Models used :
class SchedulerYear {
String year;
String month;
String date;
SchedulerYear({this.year,this.month,this.date});
#override
String toString() {
return '$year $month $date';
}
}
class SchedulerMonth {
String month;
String date;
SchedulerMonth({this.month,this.date});
#override
String toString() {
return '$month $date';
}
}
class SchedulerDate {
String date;
SchedulerDate({this.date});
#override
String toString() {
return '$date';
}
}
And finally the functions :
List<DropdownMenuItem<String>> getMenuItems(List options) {
List<DropdownMenuItem<String>> items = List();
for (String n in options) {
items.add(DropdownMenuItem(value: n, child: Text(n)));
}
return items;
}
_getYears() async {
_serviceData = await serviceHandler.fadfj; // the service response as a List
_yearData = [];
_yearList = [];
_yearItems = [];
for (int i = 0; i < _serviceData.length; i++) {
_loadData = _serviceData[i].toString();
_month = _loadData.split('/')[0];
_date = _loadData.split('/')[1];
_year = _loadData.split('/')[2];
_yearData.add(SchedulerYear(year: _year, month: _month, date: _date));
_yearList.add(_year);
}
_yearList = _yearList.toSet().toList();
_yearItems = getMenuItems(_yearList);
_selectedYear = _yearItems[0].value;
yearData = _yearData;
}
_getMonths(selectedYear) {
_dateItems = [];
_dateItems = getMenuItems(_initialDate);
_selectedDate = _dateItems[0].value;
_yearData = yearData;
_monthData = [];
_monthList = [];
_monthItems = [];
for (int i = 0; i < _yearData.length; i++) {
if (_yearData[i].year == selectedYear) {
_monthData.add(SchedulerMonth(month: _yearData[i].month, date: _yearData[i].date));
_monthList.add(_yearData[i].month);
}
}
monthData = _monthData;
_monthList = _monthList.toSet().toList();
_monthItems = getMenuItems(_monthList);
_selectedMonth = _monthItems[0].value;
}
_getDates(selectedMonth) {
_monthData = monthData;
_dateData = [];
_dateList = [];
_dateItems = [];
for (int i = 0; i < _monthData.length; i++) {
if (_monthData[i].month == selectedMonth) {
_dateData.add(SchedulerDate(date: _monthData[i].date));
_dateList.add(_monthData[i].date);
}
}
_dateList = _dateList.toSet().toList();
_dateItems = getMenuItems(_dateList);
_selectedDate = _dateItems[0].value;
}
_getYears() is called inside init() and the _getMonths(selectedYear) is called onChange of years dropdown button and _getDates(selectedMonth) on the months dropdown button

Dart - convert Webfeed to Json

I am new to dart and flutter. I am learning and trying to make an app that reads Atomic feed from the website. I am using webfeed package to accomplish this.
Here is the code I have so far -
Future<NewsModel> fetchLatestNews() async {
final response = await client.get("https://www.example.com/blog-news-list/atom/");
if(response.statusCode == 200){
var atomFeed = new AtomFeed.parse(response.body);
Map map = new Map();
for (int i = 0; i < atomFeed.items.length; i++) {
map[i]["title"] = atomFeed.items[i].title;
map[i]["link"] = atomFeed.items[i].id;
map[i]["published"] = atomFeed.items[i].published;
map[i]["summary"] = Helpers.removeAllHtmlTags(atomFeed.items[i].summary);
}
return NewsModel.fromJson(json.decode(map.toString()));
}else {
throw Exception("Failed to load post.");
}
}
And here is my news_model.dart
class NewsModel{
List<_Result> _results = [];
NewsModel.fromJson(Map<String, dynamic> parsedJson) {
List<_Result> temp = [];
for (int i = 0; i < parsedJson.length; i++) {
_Result result = _Result(parsedJson[i]);
temp.add(result);
}
_results = temp;
}
List<_Result> get results => _results;
}
class _Result {
String _title;
String _link;
String _published;
String _summary;
List<String> _categories = [];
_Result(result) {
_title = result['title'];
_link = result['link'];
_published = result['published'];
_summary = result['summary'];
for (int i = 0; i < result['category'].length; i++) {
_categories.add(result['category'][i]);
}
}
String get published => _published;
String get title => _title;
String get link => _link;
String get summary => _summary;
List<String> get categories => _categories;
}
These code didn't work. I know I am doing it wrong, but my problem will be solved if either of the following question is answered -
how could I convert AtomFeed to Json?
Or change in model that could reflect the feed without converting it to Json.
Any help will be highly appreciated
With this you already have an object that could reflect the feed:
AtomFeed atomFeed = AtomFeed.parse(response.body);
AtomFeed