Reading provider returns empty list in Riverpod - state

I have 2 functions defined in my provider file that do similar things ... filter a product list to return products by category name (getByCatName) and by brand name (getByBrandName). I invoke both functions by making similar ref.read calls to the controller file. The catList works as desired by returning the list of products for category clicked. However, the brand name function is returning empty list probably because the brand parameter is not getting passed to the getByBrandName() function. Below are snippets of code that may be helpful to get your help. I have spent 3 days checking and rechecking my code with online research but no luck. I am thinking the filter for products in categories works because I am passing arguments via a ModalRoute (...) navigation routine to desired screen. However, for brand I am not using a navigation routing as it is not applicable here.
BrandContent Screen:
class BrandContent extends HookConsumerWidget {
final String brand;
const BrandContent({required this.brand, Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
final prodBrandList = ref.watch(productControllerProvider);
final List<Product>? prodBrandName =
ref.read(productControllerProvider.notifier).getByBrandName(brand);
// print('${prodBrandName?.length}'); // it is returning zero length
return Expanded(
child: Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 0, 0),
child: MediaQuery.removePadding(
context: context,
removeTop: true,
child: Container(
margin: const EdgeInsets.only(top: 50),
child: ListView.builder(
itemCount: prodBrandName?.length,
// itemCount: prodBrandList.length,
itemBuilder: (ctx, i) {
// return BrandsNavScreen(
// id: prodBrandList[i].id,
// brand: prodBrandList[i].brand,
// title: prodBrandList[i].title,
// productCategory: prodBrandList[i].productCategoryName,
// imageUrl: prodBrandList[i].imageUrl,
// price: prodBrandList[i].price,
// );
return BrandsNavScreen(
id: prodBrandName?[i].id,
title: prodBrandName![i].title,
brand: prodBrandName[i].brand,
productCategory: prodBrandName[i].productCategoryName,
imageUrl: prodBrandName[i].imageUrl,
price: prodBrandName[i].price,
);
}),
),
ProductController that has both functions and product model.
final productControllerProvider =
StateNotifierProvider<ProductListController, List<Product>>(
(ref) => ProductListController(),
);
class ProductListController extends StateNotifier<List<Product>> {
ProductListController([List<Product>? state]) : super(state ?? <Product>[]);
#override
List<Product> get state => _products;
final List<Product> _products = [
Product(
id: 'Samsung1',
title: 'Samsung Galaxy S9',
description:
'Samsung Galaxy S9 G960U 64GB Unlocked GSM 4G LTE Phone w/ 12MP Camera - Midnight Black',
price: 50.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/81%2Bh9mpyQmL._AC_SL1500_.jpg',
brand: 'Samsung',
productCategoryName: 'Phones',
quantity: 65,
isFavorite: false,
isPopular: false),
Product(
id: 'Samsung Galaxy A10s',
title: 'Samsung Galaxy A10s',
description:
'Samsung Galaxy A10s A107M - 32GB, 6.2" HD+ Infinity-V Display, 13MP+2MP Dual Rear +8MP Front Cameras, GSM Unlocked Smartphone - Blue.',
price: 50.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/51ME-ADMjRL._AC_SL1000_.jpg',
brand: 'Samsung ',
productCategoryName: 'Phones',
quantity: 1002,
isFavorite: false,
isPopular: false),
Product(
id: 'Samsung Galaxy A51',
title: 'Samsung Galaxy A51',
description:
'Samsung Galaxy A51 (128GB, 4GB) 6.5", 48MP Quad Camera, Dual SIM GSM Unlocked A515F/DS- Global 4G LTE International Model - Prism Crush Blue.',
price: 50.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/61HFJwSDQ4L._AC_SL1000_.jpg',
brand: 'Samsung',
productCategoryName: 'Phones',
quantity: 6423,
isFavorite: false,
isPopular: true),
Product(
id: 'Apple MacBook Air',
title: 'Apple MacBook Air',
description:
'Apple MacBook Air 13.3" with Retina Display, 1.1GHz Quad-Core Intel Core i5, 16GB Memory, 256GB SSD, Space Gray (Early 2020)',
price: 1220.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/61wLbRLshAL._AC_SL1200_.jpg',
brand: 'Apple',
productCategoryName: 'Laptops',
quantity: 815,
isFavorite: false,
isPopular: true),
Product(
id: 'Apple MacBook Progag',
title: 'Apple MacBook Pro',
description:
'Apple MacBook Pro MF839LL/A 13.3in Laptop, Intel Core i5 2.7 GHz, 8GB Ram, 128GB SSD ',
price: 700.89,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/315CQ1KmlwL._AC_.jpg',
brand: 'Apple',
productCategoryName: 'Laptops',
quantity: 815,
isFavorite: false,
isPopular: false),
Product(
id: 'Apple MacBook Air',
title: 'Apple MacBook Air',
description:
'Apple MacBook Air 13.3" with Retina Display, 1.1GHz Quad-Core Intel Core i5, 8GB Memory, 256GB SSD, Silver (Early 2020)',
price: 780.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/61QRQHn0jJL._AC_SL1200_.jpg',
brand: 'Apple',
productCategoryName: 'Laptops',
quantity: 4455,
isFavorite: false,
isPopular: true),
Product(
id: 'Apple 16 MacBook Pro',
title: 'Apple 16 MacBook Pro',
description:
'Apple 16 MacBook Pro with Touch Bar, 9th-Gen 8-Core Intel i9 2.3GHz, 16GB RAM, 1TB SSD, AMD Radeon Pro 5500M 8GB, Space Gray, Late 2019 Z0Y0005J7 / Z0Y00006M',
price: 800.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/61qNHbx9LDL._AC_SL1200_.jpg',
brand: 'Apple',
productCategoryName: 'Laptops',
quantity: 885,
isFavorite: false,
isPopular: false),
Product(
id: 'Sofa Setttt',
title: 'Sofa Set',
description: 'Beverly Fine Funiture Sectional Sofa Set, 91A Black ',
price: 650.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/71P-p2sj6eL._AC_SL1500_.jpg',
brand: 'No brand',
productCategoryName: 'Furniture',
quantity: 91,
isFavorite: false,
isPopular: true),
Product(
id: 'Furniture Classroom with Teacher\'s',
title: 'Furniture Classroom with Teacher\'s',
description:
'L.O.L. Surprise! Furniture Classroom with Teacher\'s Pet & 10+ Surprises',
price: 120.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/71xytsyiHzL._AC_SL1500_.jpg',
brand: 'No brand',
productCategoryName: 'Furniture',
quantity: 815,
isFavorite: false,
isPopular: false),
Product(
id: 'Sofa Couch for Two People',
title: 'Sofa Couch for Two People',
description:
'Serta Copenhagen Sofa Couch for Two People, Pillowed Back Cushions and Rounded Arms, Durable Modern Upholstered Fabric, 61" Loveseat, Brown',
price: 1220.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/81sBT3voCPL._AC_SL1500_.jpg',
brand: 'No brand',
productCategoryName: 'Furniture',
quantity: 8100,
isFavorite: false,
isPopular: true),
Product(
id: 'Delta Children Plastic Toddler Bed',
title: 'Delta Children Plastic Toddler Bed',
description:
'Delta Children Plastic Toddler Bed, Disney Princess + Delta Children Twinkle Galaxy Dual Sided Recycled Fiber Core Toddler Mattress (Bundle)',
price: 127.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/71Rj3InxQlL._SL1500_.jpg',
brand: 'No brand',
productCategoryName: 'Furniture',
quantity: 9145,
isFavorite: false,
isPopular: false),
Product(
id: 'Outdoor Patio ',
title: 'Outdoor Patio ',
description:
'Recaceik 3 Pieces Outdoor Patio Furniture Sets Rattan Chair Wicker Set, with Cushions and Tempered Glass Tabletop, Outdoor Indoor Use Backyard Porch Garden-(Brown)',
price: 1224.88,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/81KabJxRvDL._AC_SL1500_.jpg',
brand: 'No brand',
productCategoryName: 'Furniture',
quantity: 25,
isFavorite: false,
isPopular: true),
Product(
id: 'Flash Furniture Nantucket 6 Piece',
title: 'Flash Furniture Nantucket 6 Piece',
description:
'Flash Furniture Nantucket 6 Piece Black Patio Garden Set with Table, Umbrella and 4 Folding Chairs',
price: 1220.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/81khjDZg5xL._AC_SL1500_.jpg',
brand: 'No brand',
productCategoryName: 'Furniture',
quantity: 651,
isFavorite: false,
isPopular: false),
Product(
id: 'Homall 4 Pieces Patio Outdoor Furniture Sets',
title: 'Homall 4 Pieces Patio Outdoor Furniture Sets',
description:
'Homall 4 Pieces Patio Outdoor Furniture Sets, All Weather PE Rattan Wicker Sectional Sofa Modern Manual Conversation Sets with Cushions and Glass Table for Lawn Backyard Garden Poolside(Beige)',
price: 1220.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/716-fllmUCL._AC_SL1500_.jpg',
brand: 'No brand',
productCategoryName: 'Furniture',
quantity: 594,
isFavorite: false,
isPopular: true),
Product(
id: 'Ashley Furniture Signature Design',
title: 'Ashley Furniture Signature Design',
description:
'Ashley Furniture Signature Design - Dolante Upholstered Bed - Queen Size - Complete Bed Set in a Box - Contemporary Style Checker - Gray',
price: 300.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/71QxxtRFFkL._AC_SL1232_.jpg',
brand: 'No brand',
productCategoryName: 'Furniture',
quantity: 78,
isFavorite: false,
isPopular: false),
Product(
id: 'Apple Watch Series 3',
title: 'Apple Watch Series 3',
description:
'Apple Watch Series 3 (GPS, 38mm) - Silver Aluminum Case with White Sport Band',
price: 100.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/71vCuRn4CkL._AC_SL1500_.jpg',
brand: 'Apple',
productCategoryName: 'Watches',
quantity: 156,
isFavorite: false,
isPopular: true),
Product(
id: 'Garmin Forerunner 45S',
title: 'Garmin Forerunner 45S',
description:
'Garmin Forerunner 45S, 39mm Easy-to-use GPS Running Watch with Coach Free Training Plan Support, Purple',
price: 86.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/51EWl3XsiYL._AC_SL1000_.jpg',
brand: 'No brand',
productCategoryName: 'Watches',
quantity: 142,
isFavorite: false,
isPopular: false),
Product(
id: 'Samsung Galaxy Watch Active 2',
title: 'Samsung Galaxy Watch Active 2',
description:
'Samsung Galaxy Watch Active 2 (40mm, GPS, Bluetooth) Smart Watch with Advanced Health Monitoring, Fitness Tracking , and Long Lasting Battery - Silver (US Version)',
price: 300.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/51bSW9gjoaL._AC_SL1024_.jpg',
brand: 'Samsung',
productCategoryName: 'Watches',
quantity: 167,
isFavorite: false,
isPopular: false),
Product(
id: 'Garmin vivoactive 4S',
title: 'Garmin vivoactive 4S',
description:
'Garmin vivoactive 4S, Smaller-Sized GPS Smartwatch, Features Music, Body Energy Monitoring, Animated Workouts, Pulse Ox Sensors, Rose Gold with White Band',
price: 40.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/51r2LCE3FLL._AC_SL1000_.jpg',
brand: 'No brand',
productCategoryName: 'Watches',
quantity: 659,
isFavorite: false,
isPopular: false),
Product(
id: 'Patek Philippe World',
title: 'Patek Philippe World',
description: 'Patek Philippe World Time Men\'s Watch Model 5131/1P-001',
price: 20.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/61MVdCYfbOL._AC_UX679_.jpg',
brand: 'No brand',
productCategoryName: 'Watches',
quantity: 98,
isFavorite: false,
isPopular: false),
Product(
id: 'Bell & Ross Men',
title: 'Bell & Ross Men',
description:
'Bell & Ross Men\'s BR-MNUTTOURB-PG Minuteur\' Black Carbon Fiber Dial 18K Rose Gold Tourbillon Watch',
price: 33.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/91M50AHRTKL._AC_UX569_.jpg',
brand: 'No brand',
productCategoryName: 'Watches',
quantity: 951,
isFavorite: false,
isPopular: false),
Product(
id: 'New Apple Watch Series',
title: 'New Apple Watch Series',
description:
'New Apple Watch Series 6 (GPS, 40mm) - Blue Aluminum Case with Deep Navy Sport Band ',
price: 400.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/71bf9IpGjtL._AC_SL1500_.jpg',
brand: 'Apple',
productCategoryName: 'Watches',
quantity: 951,
isFavorite: false,
isPopular: false),
Product(
id: 'New Apple Watch SE',
title: 'New Apple Watch SE',
description:
'New Apple Watch SE (GPS, 40mm) - Gold Aluminum Case with Pink Sand Sport Band',
price: 200.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/71JtUMDeBBL._AC_SL1500_.jpg',
brand: 'Apple',
productCategoryName: 'Watches',
quantity: 951,
isFavorite: false,
isPopular: false),
Product(
id: 'YAMAY Smart Watch 2020 Ver',
title: 'YAMAY Smart Watch 2020 Ver',
description:
'YAMAY Smart Watch 2020 Ver. Watches for Men Women Fitness Tracker Blood Pressure Monitor Blood Oxygen Meter Heart Rate Monitor IP68 Waterproof, Smartwatch Compatible with iPhone Samsung Android Phones',
price: 183.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/61gCtkVYb5L._AC_SL1000_.jpg',
brand: 'Apple',
productCategoryName: 'Watches',
quantity: 56,
isFavorite: false,
isPopular: true),
Product(
id: 'Samsung Galaxy Watch Active 23',
title: 'Samsung Galaxy Watch Active ',
description:
'Samsung Galaxy Watch Active (40MM, GPS, Bluetooth) Smart Watch with Fitness Tracking, and Sleep Analysis - Rose Gold (US Version)',
price: 150.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/61n1c2vnPJL._AC_SL1500_.jpg',
brand: 'Samsung',
productCategoryName: 'Watches',
quantity: 78,
isFavorite: false,
isPopular: true),
Product(
id: 'Samsung Galaxy Watch 3',
title: 'Samsung Galaxy Watch 3',
description:
'Samsung Galaxy Watch 3 (41mm, GPS, Bluetooth) Smart Watch with Advanced Health monitoring, Fitness Tracking , and Long lasting Battery - Mystic Silver (US Version)',
price: 184.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/81Iu41zFPwL._AC_SL1500_.jpg',
brand: 'Samsung',
productCategoryName: 'Watches',
quantity: 9598,
isFavorite: false,
isPopular: true),
Product(
id: 'Samsung Galaxy Watch Active2 ',
title: 'Samsung Galaxy Watch Active2 ',
description:
'Samsung Galaxy Watch Active2 (Silicon Strap + Aluminum Bezel) Bluetooth - International (Aqua Black, R820-44mm)',
price: 120.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/518qjbbuGZL._AC_SL1000_.jpg',
brand: 'Samsung',
productCategoryName: 'Watches',
quantity: 951,
isFavorite: false,
isPopular: false,
),
Product(
id: 'Huawei Watch 2 Sport Smartwatch',
title: 'Huawei Watch 2 Sport Smartwatch',
description:
'Huawei Watch 2 Sport Smartwatch - Ceramic Bezel - Carbon Black Strap (US Warranty)',
price: 180.99,
imageUrl:
'https://images-na.ssl-images-amazon.com/images/I/71yPa1g4gWL._AC_SL1500_.jpg',
brand: 'Huawei',
productCategoryName: 'Watches',
quantity: 951,
isFavorite: false,
isPopular: true),
];
List<Product>? getByCatName(String catName) {
List<Product> catList = _products
.where(
(e) => e.productCategoryName.toLowerCase() == catName.toLowerCase())
.toList();
print(catList.length);
return catList;
}
List<Product>? getByBrandName(String brandName) {
List<Product> brandList = _products
.where((e) => e.brand.toLowerCase() == brandName.toLowerCase())
.toList();
// print(brandList.length);
return brandList;
}
}
class Product extends StateNotifier<List<Product>> {
final String? id;
final String title;
final String description;
final String brand;
final double price;
final String imageUrl;
final String productCategoryName;
final int quantity;
final bool isFavorite;
final bool isPopular;
Product({
this.id,
required this.title,
required this.description,
required this.price,
required this.imageUrl,
required this.productCategoryName,
required this.isFavorite,
required this.isPopular,
required this.quantity,
required this.brand,
}) : super(<Product>[]);
}
Portion of HomeScreen where a product brand is chosen from an image swiper widget. It is the brandsNavRail screen that is blank because the returned list is empty from fact that a brand is never passed (null) when I did a debugPrint on its value.
SizedBox(
width: double.infinity,
height: 200,
child: Swiper(
onTap: (index) {
Navigator.of(context).pushNamed(
BrandsNavRail.routeName,
arguments:
ref.read(navRailProvider.notifier).selectPage(index),
);
},
viewportFraction: 0.8,
scale: 0.9,
autoplay: true,
// autoplayDisableOnInteraction: true,
itemCount: _swiperImages.length,
// itemBuilder: (context, index) =>
// Image.asset(_swiperImages[index]),
itemBuilder: (context, index) {
return Container(
decoration: kContainerDecoration.copyWith(
border: Border.all(width: 2, color: Colors.grey),
borderRadius: BorderRadius.circular(12),
color: Colors.transparent,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Image.asset(
_swiperImages[index],
fit: BoxFit.fill,
),
),
);
},
),

I solved this issue by adding a ref.read() statement to pull the brand clicked from the navRailProvider that controls navigation and displays corresponding brand page. This line of code was missing in my original code (BrandContent.dart). See code snippets below and screenshot of simulator.
BrandContent.dart:
class BrandContent extends HookConsumerWidget {
const BrandContent({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
final brandName = ref.read(navRailProvider.notifier).brands; // New line of code added
final List<Product>? prodBrandName =
ref.read(productControllerProvider.notifier).getByBrandName(brandName);
return Expanded(
child: Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 0, 0),
child: MediaQuery.removePadding(
context: context,
removeTop: true,
child: Container(
margin: const EdgeInsets.only(top: 50),
child: ListView.builder(
itemCount: prodBrandName?.length,
itemBuilder: (ctx, i) {
return BrandsNavScreen(
id: prodBrandName?[i].id,
title: prodBrandName![i].title,
brand: prodBrandName[i].brand,
productCategory: prodBrandName[i].productCategoryName,
imageUrl: prodBrandName[i].imageUrl,
price: prodBrandName[i].price,
);
}),
),
navRailProvider:
enum BrandType { apple, dell, samsung, huawei, nike, addidas, gucci, all }
final navRailProvider =
StateNotifierProvider<NavRailManager, RailView>((ref) => NavRailManager());
class NavRailManager extends StateNotifier<RailView> {
NavRailManager() : super(defaultPage);
late String brands;
static const defaultPage = RailView(BrandType.apple);
selectPage(int i) {
switch (i) {
case 0:
state = const RailView(BrandType.apple);
brands = 'Apple';
break;
case 1:
state = const RailView(BrandType.dell);
brands = 'Dell';
break;

Related

Insert Input Chips From List<String> into TextFormField Flutter on Button Click

I am having a List<String> of cities below
List<String> cities = ["Nairobi", "Tokyo", "Moscow", "Bogota",
"Helsinki", "Denver", "Stockholm", "Oslo"];
I am taking the cities list and just setting the text to TextFormField using TextEditingController upon a city being selected in showCityPickerDialog which updates the cities string list. Below is the code
TextFormField(
cursorHeight: 20,
enableInteractiveSelection: false,
readOnly: true,
focusNode: FocusNode(),
controller: TextEditingController(
text:
cities.isEmpty ? null : "$cities"),
onTap: () {
showCityPickerDialog();
},
decoration: InputDecoration(
isDense: true,
labelText: "Select Cities",
border: const OutlineInputBorder(),
suffixIcon: IconButton(
onPressed: () {
showCityPickerDialog();
},
icon: const Icon(Icons.location_city)),
),
validator: (phoneNo) {},
keyboardType: TextInputType.multiline,
maxLines: null,
)
What i would like to achieve is instead of just setting the text using TextEditingController(text: cities.isEmpty ? null : "$cities") i would like to use Chips like in below code where the number of chips inside the TextFormField will depend on the length of the list
Chip(
avatar: CircleAvatar(
backgroundColor: Colors.grey.shade800,
child: Text('City Initial'),
),
label: Text('City'),
)
Maybe you can add chips inside your TextFormField decoration as prefix Widget like this:
prefix: Row(
children: cities
.map(
(e) => Chip(
avatar: CircleAvatar(
backgroundColor: Colors.grey.shade800,
child: Text('City Initial'),
),
label: Text(e),
),
)
.toList(),
)

How to split a list in flutter by summation of the elements in flutter

I want to split a list eg L=[1,2,1,2,2,1,1,2] into sublist in flutter according to the cumulative sum of the elements equal to 4. i.e the list should be split as S=[[1,2,1],[2,2],[1,1,2]]
I am working on something similar such that I have a list of type map, I want to sum the first consecutive new unit value from the list such that if the first consecutive numbers are 30, I will split it and add the remainder of the last element to the next list
eg. I have this list
[[{id: FG00017, newunit: 20, product: {category: Ball Foods, productname: GP Semovita 4 x 2.5kg - New Pack!, itemID: FG00017, active: 1, minorderqty: 1, price: 4010, netweight: 0, unit: Bags, bagcount: 100, image: "", locationID: Apapa, locationname: Apapa}, items: 2000}, {id: FG00018, newunit: 10, product: {category: Ball Foods, productname: GP Semovita 2 x 2.5kg - New Pack!, itemID: FG00018, active: 1, minorderqty: 1, price: 2070, netweight: 0, unit: Bags, bagcount: 200, image: "", locationID: Apapa, locationname: Apapa}, items: 2000}, {id: FG00032, newunit: 1, product: {category: Ball Foods, productname: GP Goldenvita 4 x 2.5kg - New Pack, itemID: FG00032, active: 1, minorderqty: 1, price: 3445, netweight: 0, unit: Bags, bagcount: 100, image: "", locationID: Apapa, locationname: Apapa}, items: 100}]],
the first two consecutive new unit when summed is 30 so I split it like this
[[{id: FG00017, newunit: 20, product: {category: Ball Foods, productname: GP Semovita 4 x 2.5kg - New Pack!, itemID: FG00017, active: 1, minorderqty: 1, price: 4010, netweight: 0, unit: Bags, bagcount: 100, image: https:, locationID: Apapa, locationname: Apapa}, items: 2000}, {id: FG00018, newunit: 10, product: {category: Ball Foods, productname: GP Semovita 2 x 2.5kg - New Pack!, itemID: FG00018, active: 1, minorderqty: 1, price: 2070, netweight: 0, unit: Bags, bagcount: 200, image: https:, locationID: Apapa, locationname: Apapa}, items: 2000}], [{id: FG00032, newunit: 1, product: {category: Ball Foods, productname: GP Goldenvita 4 x 2.5kg - New Pack, itemID: FG00032, active: 1, minorderqty: 1, price: 3445, netweight: 0, unit: Bags, bagcount: 100, image: https:, locationID: Apapa, locationname: Apapa}, items: 100}]],
Is there any credit for unnecessary complexity? If so, a sync* function can be used.
void main() {
print(parcel([1, 2, 1, 2, 2, 1, 1, 2].iterator));
}
Iterable<List<int>> parcel(Iterator<int> input) sync* {
List<int>? group;
while (input.moveNext()) {
group = (group ?? <int>[])..add(input.current);
if (group.reduce((v, e) => v + e) >= 4) {
yield group;
group = null;
}
}
}
What to do with any members of the input that don't complete a group of at least 4 is left as an exercise for the reader.

Django Templates - How to auto increment an integer?

I'm using Django with Alpine.js. I'm trying to loop over users' images from 1 to 20. For instance, 'user-1.jpg', 'user-2.jpg', and so on and so forth. The following is, of course, not working, but at least it will give you a sense of what I'm trying to achieve:
{% load static %}
<div x-data="libs.testimonialsCircles()">
<template x-for="(item, index) in items" :key="index" hidden>
<img class="absolute rounded-full z-10 animate-float" :style="item.style" :src="`{% static img/user-${index+1}.jpg %}`" :width="item.size" :height="item.size" :alt="`User ${index+1}`" #mouseenter="active = index; commentOn = true" #mouseleave="commentOn = false" />
</template>
</div>
My JS file
export default function testimonialsCircles() {
return {
commentOn: false,
active: 0,
// each item is a testimonial avatar with a comment
items: [
{
// user-1.jpg
img: 'user-1.jpg',
size: '48', // image width / height
style: 'max-width: 7.08%;top: 29%;left: 2%;', // image absolute positioning
comment:
'A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. 🙌', // comment to be displayed on hover,
name: 'Elian Whitney',
},
{
// user-2.jpg
size: '36',
style: 'max-width:5.31%;top: 60%;left: 2%;',
comment:
'Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.',
name: 'Justice Porter',
},
{
// user-3.jpg
size: '72',
style: 'max-width: 10.62%;top: 43%;left: 13%;',
comment:
'When, while the lovely valley teems with vapour around me, and the meridian sun strikes the upper surface of the impenetrable foliage of my trees, and but a few stray gleams steal into the inner sanctuary, I throw myself down among the tall grass by the trickling stream.',
name: 'Leonel Roy',
},
{
// user-4.jpg
size: '56',
style: 'max-width: 8.26%;top: 75%;left: 14%;',
comment:
'O my friend -- but it is too much for my strength -- I sink under the weight of the splendour.',
name: 'Daniel Wolf',
},
{
// user-5.jpg
size: '64',
style: 'max-width: 9.44%;top: 11%;left: 15%;',
comment:
'I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine.',
name: 'Seamus Miranda',
},
{
// user-6.jpg
size: '80',
style: 'max-width: 11.8%;top: 32%;left: 30%;',
comment:
'I am so happy, my dear friend, so absorbed in the exquisite sense of mere tranquil existence, that I neglect my talents.',
name: 'Fiona Schultz',
},
{
// user-7.jpg
size: '50',
style: 'max-width: 7.37%;top: 65%;left: 30%;',
comment:
'I should be incapable of drawing a single stroke at the present moment.',
name: 'Monica Evans',
},
{
// user-8.jpg
size: '36',
style: 'max-width:5.31%;top: 6%;left: 33%;',
comment: 'I feel that I never was a greater artist than now.',
name: 'Jakayla Dunlap',
},
{
// user-9.jpg
size: '44',
style: 'max-width: 6.49%;top: 77%;left: 44%;',
comment:
'When, while the lovely valley teems with vapour around me, and the meridian sun strikes the upper surface of the impenetrable foliage of my trees.',
name: 'Mattie Sharp',
},
{
// user-10.jpg
size: '64',
style: 'max-width: 9.44%;top: 48%;left: 46%;',
comment:
'I should be incapable of drawing a single stroke at the present moment; and yet I feel that I never was a greater artist than now.',
name: 'Jazmyn Gaines',
},
{
// user-11.jpg
size: '72',
style: 'max-width: 10.62%;top: 16%;left: 46%;',
comment:
'One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin.',
name: 'Patrick Christensen',
},
{
// user-12.jpg
size: '64',
style: 'max-width: 9.44%;top: 65%;left: 58%;',
comment:
'His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked.',
name: 'Mike Johnson',
},
{
// user-13.jpg
size: '80',
style: 'max-width: 11.8%;top: 32%;left: 62%;',
comment:
'His room, a proper human room although a little too small, lay peacefully between its four familiar walls.',
name: 'Lyla Griffith',
},
{
// user-14.jpg
size: '48',
style: 'max-width: 7.08%; top: 6%;left: 63%;',
comment:
'Drops of rain could be heard hitting the pane, which made him feel quite sad.',
name: 'Damien Mclaughlin',
},
{
// user-15.jpg
size: '24',
style: 'max-width: 3.54%;top: 93%;left: 65%;',
comment:
'" He felt a slight itch up on his belly; pushed himself slowly up on his back towards the headboard so that he could lift his head better.',
name: 'Perry Mason',
},
{
// user-16.jpg
size: '36',
style: 'max-width:5.31%;top: 86%;left: 76%;',
comment:
'For instance, whenever I go back to the guest house during the morning to copy out the contract, these gentlemen are always still sitting there eating their breakfasts. I ought to just try that with my boss.',
name: 'Briana Friedman',
},
{
// user-17.jpg
size: '44',
style: 'max-width: 6.49%;top: 59%;left: 76%;',
comment:
'I would get kicked out on the spot.But who knows, maybe that would be the best thing for me.',
name: 'Manuel Kirk',
},
{
// user-18.jpg
size: '72',
style: 'max-width: 10.62%;top: 14%;left: 78%;',
comment:
'And it is a funny sort of business to be sitting up there at your desk, talking down at your subordinates from up there.',
name: 'Cedric Reynolds',
},
{
// user-19.jpg
size: '64',
style: 'max-width: 9.44%;top: 40%;left: 89%;',
comment: 'I ought to just try that with my boss.',
name: 'Gracelyn Wilcox',
},
{
// user-20.jpg
size: '24',
style: 'max-width: 3.54%;top: 74%;left: 91%;',
comment:
'It was half past six and the hands were quietly moving forwards, it was even later than half past.',
name: 'Jamir Henson',
},
],
};
}
I know that I probably should use {{ forloop.counter }} but I'm not sure how exactly should I use it in this type of context.

google visualization bar chart stacking two bars

I have a google visualization bar chart sample here where the data format is as given below.
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
How to make expenses and profits bar stacked where as sales is a separate bar?
At the moment the Google Charts API doesn't have this in built feature, but with some remodeling of the DataTable and Chart Options you can still achieve this.
My Solution
The Stacked Bar should contain values of only Expenses and Profit, to avoid a Stacked bar with Sales the value in the data column for Sales is represented as zero. A separate Sales bar is created by having a similar data row, but with the value of Sales present, and the rest zero. The Date data type needs to be specified in order to group all bar charts with the same date, if this isn't implemented, then there will be a gap between each bar chart with the same year.
More information on Date representation of Columns is available here.
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'year', type: 'date'},
{label: 'Sales', id: 'Sales', type: 'number'},
{label: 'Expenses', id: 'Expenses', type: 'number'},
{label: 'Profit', id: 'Profit', type: 'number'}],
[{v:new Date('2014'), f:'2014'}, 0, 400, 200],
[{v:new Date('2014'), f:'2014'}, 1000, 0, 0],
[{v:new Date('2015'), f:'2015'}, 0, 460, 250],
[{v:new Date('2015'), f:'2015'}, 1170, 0, 0],
[{v:new Date('2016'), f:'2016'}, 0, 1120, 300],
[{v:new Date('2016'), f:'2016'}, 600, 0, 0],
[{v:new Date('2017'), f:'2017'}, 0, 540, 350],
[{v:new Date('2017'), f:'2017'}, 1030, 0, 0]
]);
To achieve the stacked bar, the google charts configuration option isStacked: true is used. To avoid the vertical axis acting like a timeline with months and days, the vertical axis is formatted to display the Year using vAxis: {format: 'yyyy'}. More information on formatting is available here. To avoid spacing between different Year Bars, the feature bar: {groupWidth: '90%'} is used.
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
},
bars: 'horizontal', // Required for Material Bar Charts.
hAxis: {format: 'decimal'},
vAxis: {
format: 'yyyy'
},
height: 400,
colors: ['#1b9e77', '#d95f02', '#7570b3'],
isStacked: true,
bar: {groupWidth: '90%'}
};

How to select a card in a carousel by menu item in a docked menu list in Sencha touch?

I cannot figure out how I can retrieve a given Data item in a store (id-number) to send it to the "setActiveItem" method in a listener:
So I have a store - model:
Ext.regModel('PictureItem', {
fields: ['id', 'titel', 'url']
});
var pictureItems = new Ext.data.Store({
model: 'PictureItem',
data: [
{id:1, titel:'page 1', url:'http://placekitten.com/1024/768'},
{id:2, titel:'page 2', url:'http://placekitten.com/1024/768'},
{id:3, titel:'page 3', url:'http://placekitten.com/1024/768'},
]
});
Here is my menuList called "leftList":
var leftList = new Ext.List({
dock: 'left',
id:'list1',
width: 135,
overlay: true,
itemTpl: '{titel}',
singleSelect: true,
defaults: {
cls: 'pic'
},
store: pictureItems,
listeners:{
selectionchange: function (model, records) {
if (records[0]) {
Ext.getCmp('karte').setActiveItem(!!!Here the number of the selected Item
or respondend "id" in the data store!!!);
}
}
}
});
and the carousel....
var carousel = new Ext.Carousel({
id: 'karte',
defaults: {
cls: 'card'
},
items: [{
scroll: 'vertical',
title: 'Tab 1',
html: '<img class="orientation" alt="" src="img_winkel/titel_v.jpg">'
},
If I call
Ext.getCmp('karte').setActiveItem(2);
it works with the called card - but how can I get the number from the id of the selected item in the menu List /store????
By the way: what does mean:
if (records[0]) {
why [0]?
I FOUND THE ANSWER FOR MYSELF - IT'S EASY:
Ext.getCmp('karte').setActiveItem(records[0].get('id'), {type: 'slide', direction: 'left'});
The secret to get the record-entry is ".get()":
records[0].get('arrayfield')
So now I can change the activeItem in the carousel easely...