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;
I've 4 model that has relationship through FK.
class Journal(models.Model):
name = models.CharField(max_length=255)
class Volume(models.Model):
journal = models.ForeignKey(Journal, related_name='volumes')
number = models.IntegerField()
class Issue(models.Model):
volume = models.ForeignKey(Volume, related_name='issues')
number = models.IntegerField()
class Article(models.Model):
issue = models.ForeignKey(Issue, related_name='articles')
title = models.CharField(max_length=255)
I need a JSON format like follow structure.
journal: [
{ name: 'Volume number goes here', type: 'folder', id: 'F1',
data: [
{ name: 'Issue number goes here', type: 'folder', id: 'F1F1',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F1F1I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F1I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F1I3' },
]},
{ name: 'Issue number goes here', type: 'folder', id: 'F1F2',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F1F2I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F2I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F2I3' },
]},
]
},
{ name: 'Volume number goes here', type: 'folder', id: 'F2',
data: [
{ name: 'Issue number goes here', type: 'folder', id: 'F1F1',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F2F1I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F1I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F1I3' },
]},
{ name: 'Issue number goes here', type: 'folder', id: 'F1F2',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F2F2I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F2I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F2I3' },
]},
]
}
],
I've tried several stuff but it will cause hundred of sql queries ( because of for loops )
Any ideas ?
You can create that JSON file using exactly 4 queries. You just have to use prefetch_related.
Here is some proof of concept (for queries counter to work, you must have DEBUG=True):
from django.db import connection
journals = Journal.objects.all().prefetch_related('volumes', 'volumes__issues', 'volumes__issues__articles')
for journal in journals:
print "%s" % journal.name
for volume in journal.volumes.all():
print " %d" % volume.number
for issue in volume.issues.all():
print " %d" % issue.number
for article in issue.articles.all():
print " %s" % article.title
print len(connection.queries)
That will print simple tree of your objects and number of queries at the end, which will equal 4 (if there wasn't any queries done before in that connection). From that there is not far to create your JSON output.
In creating that exact JSON, Django REST Framework can be helpful. Assuming that you have all your serializers done and nested, feeding JournalSerializer With above queryset, will create exactly 4 queries to database.
Use select_related and prefetch_related. These methods are used in the Django ORM to do SQL JOINs, so you won't be duplicating queries.
I'm trying to create view which loads list using JSONP, but I want to reload the list when user choose a value from selectfield.
My code:
var distance = 50;
Ext.define('MyApp.view.ListUpdate', {
extend: 'Ext.Container', //Ext.navigation.View
xtype: 'listUpdate',
requires: [
'Ext.dataview.List',
'Ext.data.proxy.JsonP',
'Ext.data.Store',
'Ext.field.Select'
],
config: {
style: ' background-color:white;',
layout: 'vbox',
items:
[
{
xtype: 'toolbar',
docked: 'top',
title: 'List update',
minHeight: '60px',
items: [
{
ui: 'back',
xtype: 'button',
id: 'backButton', //taki sam id jak w view.GdzieJestem
text: 'Back',
},
{
minHeight: '60px',
right: '5px',
html: ['<img src="resources/images/myImage.png"/ style="height: 100%; ">',].join(""),
},
],
},
{
xtype: 'fieldset',
title: 'Choose distance',
items: [
{
xtype: 'selectfield',
id: 'selectField',
options: [
{text: '50km', value: 50},
{text: '100km', value: 100},
{text: '150km', value: 150},
{text: '200km', value: 200},
{text: '250km', value: 250},
{text: '300km', value: 300},
{text: '350km', value: 350},
{text: '400km', value: 400},
{text: '450km', value: 450},
{text: '500km', value: 500},
{text: '550km', value: 550},
{text: '600km', value: 600},
],
listeners: {
change: function (select, newValue, oldValue) {
// console.log('change', newValue.data.value);
console.log(Ext.getCmp('selectField').getValue());
distance = Ext.getCmp('selectField').getValue();
} // change
} // listeners
}
]
},
{
xtype: 'list',
style: ' background-color:white;',
itemTpl: '<h2>{company}, {firstName} {lastName}</h2><p> <span style="color:blue;">{city}, {street}, tel: {telephoneNumber}, </span><span style="color:orange;"> odległość: {distance}km</span></p>',
flex: 1,
store: {
autoLoad: true,
fields : ['company', 'firstName', 'lastName', 'city', 'street', 'telephoneNumber', 'distance'],
proxy: {
type: 'jsonp',
url: 'http://192.168.1.15:8080/MyServer/agents/list?userLat='+lat+'&userLon='+lon+'&distance='+distance+'',
reader: {
type: 'json',
rootProperty: 'agents'
}
}
}
}
]
}
});
My second question is: Have you any idea why geolocation works when app runs in Chrome but when it runs on device natively, geolocation doesnt work.
Code:
var lat = 0;
var lon = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
lat = position.coords.latitude;
lon = position.coords.longitude;
//Ext.Viewport.setActiveItem(Ext.create('Proama.view.WyszukajAgenta'));
},
function (error)
{
switch(error.code)
{
case error.TIMEOUT:
alert ('Timeout');
break;
case error.POSITION_UNAVAILABLE:
alert ("Postition unavailable");
break;
case error.PERMISSION_DENIED:
alert ('Permission denied');
break;
case error.UNKNOWN_ERROR:
alert ('Unknown error');
break;
}
}
);
}
else {
alert('Problem with device.');
}
For question 1, I would just reload the list component's store on select change. The way you have this setup you will need to access the list component's store via the list. for example, on change event:
change: function(select, newValue, oldValue){
var items = select.getParent().getParent().getItems(); // access parent's parent's items
var list = items[1]; // list is the second item in the parent's
list.getStore().load(); // reload the list's store
}
Ideally you should abstract the store and register it at the application level (if you are developing in MVC format). With the store abstracted you would be able to call Ext.getStore('MyStore').load(); anywhere in your application.
As for question 2, when you wrap the app in a native shell, in my experience HTML5 geolocation does not work. You will need to make a bridge to the native GPS calls using a tool like PhoneGap (http://docs.phonegap.com/en/1.9.0/cordova_geolocation_geolocation.md.html#Geolocation)
Hope this helps.