flutter send list to another class - list

Is there a way to send list from class to another class without any button click ?
I tried
MesFavorisOn(arr: Items)
But it gives me error
thanks.
I have a list on class named Prochaines
List<Item> Items = [
Item(
nb: 0,
Vip: true,
Image: "assets/images/watch-gt2-listimage-Matte-Black.png",
TimeLeft: "04h 27m 03s",
ParticpantsPercent: "65%",
Title: "HUAWEI SMART WATCH GT2",
MagasinPrice: "899DT",
DepartPrice: "1 DT",
Remise: "279DT",
ButtonText: "Participez à 6 Dt",
),
Item(
nb: 1,
Vip: false,
Image: "assets/images/xiaomi-redmi-7a.png",
TimeLeft: "04h 27m 03s",
ParticpantsPercent: "20%",
Title: "REDMI 7A BLACK",
MagasinPrice: "4 999 DT",
DepartPrice: "1 DT",
Remise: "40DT",
ButtonText: "Participez gratuiment",
),
Item(
nb: 2,
Vip: false,
Image: "assets/images/xiaomi-redmi-7a.png",
TimeLeft: "04h 27m 03s",
ParticpantsPercent: "65%",
Title: "REDMI 7A BLACK",
MagasinPrice: "4 999 DT",
DepartPrice: "1 DT",
Remise: "40DT",
ButtonText: "Participez gratuiment",
),
];
i wanna send it to a class named MesFavorisOn which has a constructor
List<Item> arr = [];
MesFavorisOn({required this.arr});

You did it right but you have problem in your ui objects . I guess you didn't give fixed height to your ListView

Related

Retrieving information from nested lists (Flutter)

I have what appears to most likely be a simple problem for everyone else, yet for some reason I can't seem to fix. I am a complete Flutter noob, but with coding experience. I am hoping to get tips around structuring data, and I have created a list which houses another list, like so:
class Store{
final String name;
final String image;
final List <Product> products; // this is defined in another class, and it requires a name(string), description(string), price (double)
Store({required this.name, required this.image, required this.features, required this.price})
List <Store> store= [
Store(name: "Ikea:, image: "ikealogo.png",
products :[Product(name: "wood table", description: "a very nice wood table", price: 12.50),
Product(name: "comfy chair", description: "a very nice leather chair", price: 10.50),
Product(name: "awesome lamp", description: "an ultra bright lamp", price: 5.50),]),
Store(name: "Bestbuy:, image: "bestbuylogo.png",
products :[Product(name: "television", description: "a very nice television", price: 350.00),
Product(name: "radio", description: "a very loud radio", price: 15.50),
Product(name: "cellphone", description: "a very small phone", price: 78.50),]),
];
}
Basically I have like 20 more of these things, following the same format.
Now for my problem, I can't seem to create a list out of the "Product" info nested within "Store". I can create lists with Store just fine, and I can call on the name and logo for all parts of the UI. My challenge is getting the Product information after a Store is selected, as the code I use currently shows "Iterable" when I hover over it. On the other hand, I get "List" just fine when I define or call the store list on another route.
#override
Widget build(BuildContext context) {
final product = Store.store.map((store) {
final productlist = store.products.toList();
});
I know that my code may not make any sense, and you can give me any kind of recommendations to alter the data structure altogether. For now (without using databases just yet), I want to show what products are available based on the store selected.
I hope everyone has a safe and productive day. Thank you!
In the example below I have set up a drop down button to show the list of stores. Selection causes a repaint which show the products in the selected store.
Hope the helps.
class _MyHomePageState extends State<MyHomePage> {
int _storeIdx = 0;
Store get _currentStore => storeList[_storeIdx];
List<Store> storeList = [
Store(name: "Ikea:", image: "ikealogo.png", products: [
Product(name: "wood table", description: "a very nice wood table", price: 12.50),
Product(name: "comfy chair", description: "a very nice leather chair", price: 10.50),
Product(name: "awesome lamp", description: "an ultra bright lamp", price: 5.50),
]),
Store(name: "Bestbuy:", image: "bestbuylogo.png", products: [
Product(name: "television", description: "a very nice television", price: 350.00),
Product(name: "radio", description: "a very loud radio", price: 15.50),
Product(name: "cellphone", description: "a very small phone", price: 78.50),
]),
];
#override
Widget build(BuildContext context) {
int _offset = 0;
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton(
value: _storeIdx,
items: storeList
.map((Store s) => DropdownMenuItem(
child: Text(s.name),
value: _offset++,
))
.toList(),
onChanged: (int? value) {
setState(() {
_storeIdx = value ?? 0;
});
},
hint: const Text('Select store')),
Text("Currently ${_currentStore.name}"),
..._currentStore.products.map((Product p) => Text(p.name)).toList(),
],
),
),
);
}
}
Note that the spread operator ... is quite useful when you are trying to flatten a hierarchy of widgets.
Also, sometimes in Flutter, there is a tendency to have one humongous build method. Sometimes it is clearer to break a screen in separate widgets or to break the build method into several methods each returning an array of widgets that can then be consolidated in the build method.
I can't help but notice that store inside of Store class is not a static variable which means Store.store should not be accessible. However, if store were a static variable inside Store class Store.store will work.
So,
class Product {
String name;
Product(this.name);
#override
String toString() {
return "Product($name)";
}
}
class Store {
List<Product> products;
Store(this.products);
static List<Store> stores = [
Store([
Product("Soap"),
Product("Bar"),
]),
Store([
Product("Sponge"),
Product("ChocoBar"),
]),
];
}
void main() {
print(Store.stores[0].products);
print(Store.stores[1].products);
}
Will yield an output of :
[Product(Soap), Product(Bar)]
[Product(Sponge), Product(ChocoBar)]
which is what we expect to find.

How to count category value of array of List

let's say I have a list like the example below
<Categories>myList = [
Categories(
nameCategory: 'Book',
amount: '20'
),
Categories(
nameCategory: 'Book',
amount: '40'
),
Categories(
nameCategory: 'Food',
amount: '20'
),
Categories(
nameCategory: 'Food',
amount: '15'
),
];
How I can combine the duplicate values of that list and count the value of the list based on name ??
I can combine the list and the count value of the list but that only works just in a general list like sum total
what I want to do is make a new List but only combine several parts that share the same property like the same category or same class like that
this is an example what I want to achieve
<Categories> anotherList= [
Categories(
nameCategory: 'Book',
amount: '60'
),
Categories(
nameCategory: 'Food',
amount: '35'
),
];
I would replace your List<Categories> with a Map<String, Categories>. Then you can easily look up the Categories object given its name and mutate the existing Categories object. For example, something like:
var mergedCategories = <String, Categories>{};
for (var categories in myList) {
var name = categories.nameCategory;
var amount = categories.amount;
(mergedCategories[name] ??= Categories(nameCategory: name, amount: 0))
.amount += amount;
}
You're essentially trying to get an aggregate value from a list, which is what List.fold is meant to help with.
Here's an example of how you might use it:
class Category {
final String name;
int amount;
Category({required this.name, required this.amount});
String toString() => "Category(name: $name, amount: $amount)";
}
void main() {
final categories = [
Category(
name: 'Book',
amount: 20
),
Category(
name: 'Book',
amount: 40
),
Category(
name: 'Food',
amount: 20
),
Category(
name: 'Food',
amount: 15
),
];
/**
* Here is where the aggregation is done
*/
final List<Category> aggregated = categories.fold([], (list, item) {
try {
// Check whether the category is already in the aggregate
final existingCategory = list.firstWhere((c) => c.name == item.name);
// Category is already in the list, so just add the amount of the current item.
existingCategory.amount += item.amount;
return list;
} catch (_) {
// The category has not yet been added - so add it here
list.add(item);
return list;
}
});
print(aggregated);
}
I've changed your category class a bit for simplicity, but the principle should be the same. You can read more about the fold function here: https://api.dart.dev/stable/2.13.4/dart-core/Iterable/fold.html
A pretty straightforward method is by using the groupBy function provided by the collection.dart package.
import 'package:collection/collection.dart';
groupBy<Categories, String>(list, (c) => c.nameCategory).values.map(
(list) => list.reduce(
(a, b) => new Categories(a.nameCategory, a.amount + b.amount)
)
);

Making TabBarView dynamically in flutter

Situation:
I have two lists,tabsText and mainListAllPlantDetailsList1.
tabsText
List<String> tabsText = ["Top","Outdoor","Indoor", "Seeds", "Flowers"];
mainListAllPlantDetailsList1
List<PlantDetails> mainListAllPlantDetailsList1 = [
PlantDetails(
indexNumber: 0,
category: "flower",
plantName: "Lamb's Ear",
price: 147,
description: "This is the Lamb's Ear flower"
),
PlantDetails(
indexNumber: 1,
category: "seeds",
plantName: "Lotus",
price: 120,
description: "This is the lotus seeds"
),
PlantDetails(
indexNumber: 2,
category: "indoor",
plantName: "Hughusi Yoon",
price: 147,
description: "This is the Hughusi Yoon indoor"
),
PlantDetails(
indexNumber: 3,
category: "outdoor",
plantName: "lily",
price: 120,
description: "This is the lily outdoor"
),
];
Details:
I have made the TabBar using for loop in the tabsText list. Now I am again making the TabBarView using for loop and I tried like this
tabViewerMaker(){
List<Widget> tabBarView = List();
for(var i = 0; i<tabsText.length;i++){
for( var j =0; j<mainListAllPlantDetailsList1.length;j++){
if(tabsText[i] == mainListAllPlantDetailsList1[j].ca){
tabBarView.add(
Text("We found category"+tabsText[i])
);
}
else{
continue;
}
}
}
}
Here, I have checked the tabsText and mainListAllPlantDetailsList1. If the String of particular index of tabsText is equal to particular index of mainListAllPlantDetailsList1 then, generate a widget,
Text("We found category"+tabsText[i])
otherwise just continue. And I have made a list of type widget and added all the text widget, but while calling the function tabViewerMaker Why does it give error?
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building Container(bg: BoxDecoration(color:
Color(0xffffffff)), constraints: BoxConstraints(w=Infinity, h=317.0)):
The getter 'key' was called on null.
Question:
How can I achieve the desired function using for loop or feel free to give any suggestion?

boost: read_json: reading multiple lines

When reading the below JSON data, am getting invalid code sequence exception
in read_json.
{
"_ID":"18",
"_Record":"1",
"_BreakPageMessage":"abcd: 137
Product: ID: 1234
Description: 23456 abcdfm
CustomerId: 23456
Component Id: 3456
Description: 12345 Admn RC - up
count: 40
Sides 2
Tarnish:
size: 125 x 205
Memo:"
}
_BreakPageMessage property has multiple lines. If we give it as single line everything works fine.
This _BreakPageMessage doesn't have any umlaut characters.
boost::property_tree::read_json( file, pt );
Can anyone tell is there anyway to read json that has multiple lines of property data using boost.We are using C++ and boost.
Newlines are not valid characters in JSON strings, your data isn't JSON.
You could escape them
{
"_ID":"18",
"_Record":"1",
"_BreakPageMessage":"abcd: 137\r\n Product: ID: 1234\r\n Description: 23456 abcdfm\r\n CustomerId: 23456\r\n Component Id: 3456\r\n Description: 12345 Admn RC - up\r\n count: 40\r\n Sides 2\r\n Tarnish:\r\n size: 125 x 205\r\n Memo:"
}
or use a sub-object
{
"_ID":"18",
"_Record":"1",
"_BreakPageMessage":{
"abcd": 137,
"Product": { "ID": 1234 },
"Description": "23456 abcdfm",
"CustomerId": "23456",
"Component Id": "3456",
"Description": "12345 Admn RC - up",
"count": "40",
"Sides": "2",
"Tarnish": { size: "125 x 205" },
"Memo":""
}
}

Couchbase View _count Reduce For Given Keys

I am trying to write a view in Couchbase using a reduce such as _count which will give me a count of the products at an address.
I have some documents in the database in the following format;
Document 1
{
id: 1,
address: {
street: 'W Churchill St'
city: 'Chicago',
state: 'IL',
},
product: 'Cable'
}
Document 2
{
id: 2,
address: {
street: 'W Churchill St'
city: 'Chicago',
state: 'IL',
},
product: 'Cable'
}
Document 3
{
id: 3,
address: {
street: 'W Churchill St'
city: 'Chicago',
state: 'IL',
},
product: 'Satellite'
}
Document 4
{
id: 4,
address: {
street: 'E Foster Rd'
city: 'New York',
state: 'NY',
},
product: 'Free To Air'
}
I already have a view which gives me all the products at an address which uses a composite key such as;
emit([doc.address.street, doc.address.city, doc.address.state], null)
Now this leads me on to the actual problem, I want to be able to get a count of products at a address or addresses.
I want to be able to see for an array of "keys"
['W Churchill St','Chicago','IL']
['E Foster Rd','New York','NY']
which products and a count of them. So i would expect to see in my results.
'Cable' : 2,
'Satellite': 1,
'Free To Air': 1
however if I specified only this "key",
['W Churchill St','Chicago','IL']
I would expect to see
'Cable' : 2,
'Satellite': 1
How to write my view to accommodate this?
The solution to this was to append my product to the key like so;
emit([doc.address.street, doc.address.city, doc.address.state, doc.product], null)
Then using;
?start_key=[street,city,state]&end_key=[street,city,state,{}]&group_level=4
Result:
{"rows":[
{"key":['W Churchill St','Chicago','IL','Cable'], "value":2},
{"key":['W Churchill St','Chicago','IL','Satellite'], "value":1}
]}
I would then need to repeat this query for each of the addresses and sum the results.