Flutter RangeError (index): Invalid value: Only valid value is 0: 2 - flutter

I can't fetch the initial default address 0 in the next username. It is often a problem when a large number of addresses are found in the list of addresses.
after some fixes type 'sting' is not a subtype of type 'int' of 'index'
The data in the address will be included in the same set of items.
Please help me I am practicing fetch api
This is Code
List<Items> _list = [];
List<Items> _search = [];
var loading = false;
Future fetchMos() async {
setState(() {
loading = true;
});
_list.clear();
var client = http.Client();
String mosUrl =
'';
var url = Uri.parse(mosUrl);
var headers = {
'Client-Token': '',
};
var response = await client.get(url, headers: headers);
if (response.statusCode == 200) {
var data = jsonDecode((utf8.decode(response.bodyBytes)))['items'];
setState(() {
for (var index in data) {
_list.add(Items.fromJson(index));
loading = false;
}
});
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
fetchMos();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
),
body: ListView.builder(
itemBuilder: (context, index) {
if (_list.length > 0) {
return _listItem(index);
} else {
return Center(child: CircularProgressIndicator());
}
},
itemCount: _list.length,
),
);
}
_listItem(index) {
return Card(
elevation: 3,
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 5),
child: Text(
"${_list[index].name} ${_list[index].custnum}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontFamily: "supermarket"),
),
),
TextButton(
child: const Text(
'แก้ไข',
style: TextStyle(fontFamily: "supermarket", fontSize: 14),
),
onPressed: () {/* ... */},
),
],
),
Padding(
padding: const EdgeInsets.all(5),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
'bill To / Ship To : ${_list[index].address![index].shipto.toString()}',
style: TextStyle(
color: Colors.black,
fontSize: 16,
fontFamily: "supermarket"),
),
],
),
),
Padding(
padding: const EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"ที่อยู่ : ${_list[index].address![index].addr1.toString()}",
style: TextStyle(
color: Colors.black,
fontSize: 16,
fontFamily: "supermarket"),
),
],
),
),
],
),
);
}
}
This is json
{
"items": [
{
"custnum": "",
"name": "",
"address": [
{
"shipto": 0,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 1,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 2,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 3,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
}
]
},
{
"custnum": "",
"name": "",
"address": [
{
"shipto": 0,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 1,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 2,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 3,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
}
],

Text(
'bill To / Ship To : ${_list[index].address![index].shipto.toString()}',
style: TextStyle(
color: Colors.black, fontSize: 16, fontFamily: "supermarket"),
),
As per the above code, you using the same index for _list and address array. so maybe that will create this issue.
${_list[index].address![index].shipto.toString()}
I don't think this is right bcz when your index is 10 then
_list[10].address![10].shipto.toString()
if the address has not 10 elements then it will throw that exception.
and the same things to this code
"ที่อยู่ : ${_list[index].address![index].addr1.toString()}"

Related

Is there any way to show the unique value in Dropdownbutton list?

My code is :
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text.rich(
TextSpan(
children: [
TextSpan(
text: 'Select District',
style: getSemiBoldStyle(
color: Colormanager.lightGrey,
fontSize: AppSize.s14),
),
TextSpan(
text: AppStrings.star,
style: getSemiBoldStyle(
color: Colormanager.red,
fontSize: AppSize.s14),
),
],
),
),
const SizedBox(
height: AppSize.s4,
),
DropdownSearch<CoverageArea>(
popupProps: PopupProps.menu(
showSearchBox: true,
// disabledItemFn: (String s) => s.startsWith('I'),
searchFieldProps: TextFieldProps(
style: getBoldStyle(
color: Colormanager.black,
fontSize: FontSize.s15),
),
itemBuilder: (context, item, isSelected) =>
isSelected
? Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
item.district!,
style: getBoldStyle(
color: Colormanager.primary),
),
)
: Container(
padding: const EdgeInsets.all(8.0),
margin: const EdgeInsets.only(
bottom: 4),
color: Colormanager.lightGrey
.withOpacity(0.2),
child: Text(
item.district!,
style: getBoldStyle(
color: Colormanager.black,
fontSize: FontSize.s15),
),
),
),
items: controller.coverageAreas,
dropdownDecoratorProps: DropDownDecoratorProps(
baseStyle:
getSemiBoldStyle(color: Colormanager.black),
dropdownSearchDecoration: const InputDecoration(
// labelText: "Menu mode",
// hintText: "country in menu mode",
),
),
onChanged: (value) {
controller.selectedDistrict = value;
controller.selectDistrict.value =
value!.district.toString();
},
itemAsString: (item) => item.district.toString(),
// selectedItem: controller.selectArea.value,
),
],
),
and the api call show me :
{
"Status": true,
"message": "Coverage Area List",
"data": [
{
"id": 898,
"inside": 0,
"zone_name": "OSD Operation",
"district": "Barguna",
"area": "Barguna Sadar",
"district_id": 35,
"zone_id": 14,
"post_code": null,
"h_delivery": null,
"oneRe": null,
"oneUr": null,
"plusRe": null,
"plusUr": null,
"cod": null,
"insurance": null,
"status": 0,
"created_at": "2023-01-17 15:40:08",
"updated_at": "2023-01-17 15:40:08"
},
{
"id": 897,
"inside": 0,
"zone_name": "OSD Operation",
"district": "Barguna",
"area": "Taltoly",
"district_id": 35,
"zone_id": 14,
"post_code": null,
"h_delivery": null,
"oneRe": null,
"oneUr": null,
"plusRe": null,
"plusUr": null,
"cod": null,
"insurance": null,
"status": 0,
"created_at": "2023-01-17 15:39:49",
"updated_at": "2023-01-17 15:39:49"
},
{
"id": 896,
"inside": 0,
"zone_name": "OSD Operation",
"district": "Barguna",
"area": "Amtoly",
"district_id": 35,
"zone_id": 14,
"post_code": null,
"h_delivery": null,
"oneRe": null,
"oneUr": null,
"plusRe": null,
"plusUr": null,
"cod": null,
"insurance": null,
"status": 0,
"created_at": "2023-01-17 15:39:29",
"updated_at": "2023-01-17 15:39:29"
},
{
"id": 895,
"inside": 0,
"zone_name": "OSD Operation",
"district": "Barguna",
"area": "Betage",
"district_id": 35,
"zone_id": 14,
"post_code": null,
"h_delivery": null,
"oneRe": null,
"oneUr": null,
"plusRe": null,
"plusUr": null,
"cod": null,
"insurance": null,
"status": 0,
"created_at": "2023-01-17 15:39:05",
"updated_at": "2023-01-17 15:39:05"
},
{
"id": 891,
"inside": 0,
"zone_name": "OSD Operation",
"district": "Barishal",
"area": "Barisal Bandor Thana",
"district_id": 33,
"zone_id": 14,
"post_code": null,
"h_delivery": null,
"oneRe": null,
"oneUr": null,
"plusRe": null,
"plusUr": null,
"cod": null,
"insurance": null,
"status": 0,
"created_at": "2023-01-17 15:35:28",
"updated_at": "2023-01-17 15:35:28"
},
so on..............
I want to show Barguna district just once and area in dependable dropdownbutton in next. but how can i do it???
This is the output
how can i just show one name just once???
While there are multiple items contains single value, I will suggest you to use String dataType instead of CoverageArea. then you can create a set of string from data.
So the item will be like
final List<String> items = controller.coverageAreas.map((e)=> e.district.trim()).toSet().toList();
now use this items on dropdown. and the value will be return as String DropdownSearch<String>(

RangeError (index): Invalid value: Only valid value is 0: 1 flutter fetch api

I can't fetch the next address
but I can fetch sequence shipto 0
RangeError (index): Invalid value: Only valid value is 0: 1
after some fixes type 'sting' is not a subtype of type 'int' of 'index'
The data in the address will be included in the same set of items.
Please help me I am practicing fetch api
List<dynamic> pos = <dynamic>[];
bool isLoading = false;
#override
void initState() {
super.initState();
this.fetchMos();
}
Future fetchMos() async {
var client = http.Client();
String mosUrl =
',';
var url = Uri.parse(mosUrl);
var headers = {'Client-Token': ''};
var response = await client.get(url, headers: headers);
if (response.statusCode == 200) {
var items = jsonDecode((utf8.decode(response.bodyBytes)))['items'];
setState(() {
pos = items;
isLoading = false;
});
} else {
setState(() {
pos = [];
isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
),
body: ListView.builder(
itemBuilder: (context, index) {
if (pos.length > 0) {
return _listItem(index);
} else {
return Center(child: CircularProgressIndicator());
}
},
itemCount: pos.length + 1,
),
);
}
_listItem(index) {
return Card(
child: ListTile(
leading: const CircleAvatar(
child: Icon(Icons.emoji_emotions),
),
title: Text(
pos[index]['addr1'],
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
pos[index]['shipto'],
),
),
);
}
{
"items": [
{
"custnum": "",
"name": "",
"address": [
{
"shipto": 0,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 1,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 2,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 3,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
}
]
}
],
"total_records": 1,
"total_pages": 1,
"current_page": 1
Currently your variable pos does not contain addresses. You should add the following code after var items = jsonDecode((utf8.decode(response.bodyBytes)))['items'];
var addresses = (items[0] as Map<String, dynamic>)['address'] as List;
setState(() {
pos = addresses;
loading = false;
});
Then in ListView.builder change parameter itemCount to pos.length.
Lastly, you are trying to give integer as parameter to Text widget, which only accepts String, so change current code to the following.
Text(
pos[index]['shipto'].toString(),
)
Remark: Learn about data models and JSON serialization in Dart, don't use map/json, but try using models.
If you set the itemCount of ListView.builder widget, you'll get an index error.
Try changing your code to this
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
),
body: ListView.builder(
itemBuilder: (context, index) {
if (pos.length > 0) {
return _listItem(index);
} else {
return Center(child: CircularProgressIndicator());
}
},
itemCount: pos.length, // change here
),
);
}

how to check value in list empty or not and if not get the value

I am getting a list from servers like this
[
{
"Date": "2022-10-21",
"Wages": [
{
"Name": "101 Working hours",
"Balance": "8.00",
"Date": "2022-10-21",
"ShiftName": "AU128"
},
{
"Name": "102 Bonus pay",
"Balance": "3:48",
"Date": "2022-10-21",
"ShiftName": ""
},
{
"Name": "110 Split Shift",
"Balance": "1:00",
"Date": "2022-10-21",
"ShiftName": ""
},
{
"Name": "111 Wage reduction",
"Balance": "1:00",
"Date": "2022-10-21",
"ShiftName": ""
}
]
},
]
I want to get ShiftName if it is not empty and shows at FE. shift name is in Wages List
Text(
Wages[i].shiftName ?? "",
style: wageTextStyle,
),
I try to use List.any((any) => any.containsValue());
but I do not know which value I get from server because shiftName can be changed
my API calling method from provider Consumer
Consumer<EmployeeWageAccountsProvider>(
builder: (context, data, child) {
if (!data.isLoading) {
int length = data.getEmployeeAccountsData!.length;
if (data.getEmployeeAccountsData!.isNotEmpty) {
wageAccountsData = data.getEmployeeAccountsData!;
return ListView.builder(
itemCount: length,
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemBuilder: (context, i) {
return WageAccountsCard(
date: Helper.formatStringDate(
wageAccountsData[i].date!),
shiftName: wageAccountsData[i].wages!
[i].shiftName!.isEmpty ? "":wageAccountsData[i].wages!
[i].shiftName,
wages: wageAccountsData[i].wages,
);
},
);
}
return noDataFound(context, 50);
}
return const WageAccountsShimmer();
}),
wage accounts card to displaying data to user
class WageAccountsCard extends StatelessWidget {
final String? date;
final String? shiftName;
final List<Wages>? wages;
const WageAccountsCard(
{Key? key,
this.date,
this.shiftName,
this.wages})
: super(key: key);
#override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(10),
padding: const EdgeInsets.all(8),
decoration: CustomBoxDecoration.cardDecoration(context,
shadow: true),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
shiftName ?? "",
style: wageTextStyle,
),
Text(
date.toString(),
style: wageTextStyle,
),
],
),
SizedBox(
height: Styles.height(context) * 0.01,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
S.of(context).wage_type,
style: cTextStyle,
),
Text(
S.of(context).balance,
style: cTextStyle,
),
],
),
const Divider(
color: Colors.black,
),
]
),
);
}
}
shiftName ?? "", used to return default value on null case.
You are getting empty String, therefore you can do
shiftName.isEmpty ? "onEmptyCaseValue" : shiftName
return shiftName.isEmpty ? Center(child: Text('Empty')) : Text(
shiftName ?? "",
style: wageTextStyle,
),
wageAccountsData[i].wages!
[i].shiftName!.isEmpty ? "":wageAccountsData[i].wages[i].shiftName,
insted of this just write like this
wageAccountsData[i].wages![i].shiftName ?? "Default Text",

error: Null check operator used on a null value OR List<dynamic> is not a subtype of type Map<String, dynamic>

fetch Two different pages api with same uniq id
I want the user_uniq_id of the API of the button and the user_uniq_id of the API of the team_list to match and show the data of its user after the match.
this code is for first File
This code is of the button that is coming from the api
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:practice/left_team.dart';
import 'package:http/http.dart' as http;
class Button extends StatefulWidget {
#override
_ButtonState createState() => _ButtonState();
}
class _ButtonState extends State<Button> {
var api = Uri.parse('http://192.***.***.***/flutter/teamApi.php');
var response;
var teamApi;
#override
void initState() {
super.initState();
fetchData();
}
fetchData() async {
response = await http.get(api);
print(response.body);
teamApi = jsonDecode(response.body);
setState(() {});
}
#override
Widget build(BuildContext context) {
var color = 0xff453658;
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xff392850),
title: Row(
children: [
InkWell(
onTap: () {
Navigator.pop(context);
},
child: Icon(Icons.arrow_back)),
SizedBox(
width: 10.0,
),
Text(
"Income",
style: TextStyle(fontStyle: FontStyle.italic),
),
],
),
actions: [
IconButton(
icon: Icon(Icons.person),
onPressed: () => print("open cart"),
),
],
),
body: Column(
children: [
Container(
margin: const EdgeInsets.all(20.0),
padding: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
border: Border.all(width: 2, color: Color(color))),
child: Row(
children: [
Text(
"Total Income:",
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic),
),
SizedBox(
width: 10.0,
),
Text(
"Rs.2000",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic),
),
],
),
),
SizedBox(
height: 20.0,
),
Flexible(
child: Container(
child: GridView.count(
childAspectRatio: 1.0,
padding: EdgeInsets.only(left: 16, right: 16),
crossAxisCount: 3,
crossAxisSpacing: 18,
mainAxisSpacing: 18,
children: List.generate(
teamApi.length,
(index) => GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
LeftTeam(teamData: teamApi[index])),
);
},
child: Container(
decoration: BoxDecoration(
color: Color(0xff00ffff),
borderRadius: BorderRadius.circular(10)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Text(teamApi[index]["teamType"],
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600)),
),
],
),
),
),
),
),
),
),
],
),
);
}
}
This is API data of button
[{"teamType":"direct team","team_name":"platinum","team_number":"234","team_uniq_id":"1","team_last_update":"10-may-2021"},{"teamType":"left team","team_name":"gold","team_number":"356","team_uniq_id":"2","team_last_update":"10-may-2021"},{"teamType":"right team","team_name":"silver","team_number":"876","team_uniq_id":"3","team_last_update":"10-may-2021"}]
this is code for second file.
this is model part.
class MyData {
List<Results> user = [];
MyData.fromJson(Map<String, dynamic> json) {
// previous = json['previous'];
// next = json['next'];
if (json['results'] != null) {
user = <Results>[];
json['results'].forEach((v) {
user.add(new Results.fromJson(v));
});
}
}
}
class Results {
String user_name = "";
String user_mother_name = "";
String user_address = "";
String user_mobile = "";
String user_sponsor_id = "";
String sponsor_id = "";
String email = "";
String city = "";
String state = "";
String dob = "";
Results.fromJson(Map<String, dynamic> json) {
user_name = json['user_name'];
user_mother_name = json['user_mother_name'];
user_address = json['user_address'];
user_mobile = json['user_mobile'];
user_sponsor_id = json['user_sponsor_id'];
email = json['email'];
city = json['city'];
state = json['state'];
dob = json['dob'];
}
}
this provider of api link.
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import 'package:practice/LeftTeamFile/model/myData.dart';
class MyHomePageProvider extends ChangeNotifier {
MyData? data;
Future getData(context) async {
var url = Uri.parse(
var url = Uri.parse('http://192.***.***.***/flutter/team_list.php');
var response = await http.get(url);
print("res${response.body}");
var mJson = json.decode(response.body);
this.data = MyData.fromJson(mJson);
this.notifyListeners();
this is teamList part .
import 'package:flutter/material.dart';
import 'package:practice/LeftTeamFile/provider/myHomePageProvider.dart';
import 'package:provider/provider.dart';
class TeamList extends StatefulWidget {
final teamData;
const TeamList({Key? key, this.teamData}) : super(key: key);
#override
_TeamListState createState() => _TeamListState();
}
class _TeamListState extends State<TeamList> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
Container(
padding: EdgeInsets.all(10.0),
height: 100.0,
color: Color(0xffedbf6b),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(
Icons.list_alt,
color: Colors.white,
),
Text(
widget.teamData['team_uniq_id'],
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
),
),
],
),
]),
),
SizedBox(
height: 10.0,
),
Stack(
children: [
ChangeNotifierProvider<MyHomePageProvider>(
create: (context) => MyHomePageProvider(),
child: Consumer<MyHomePageProvider>(
builder: (context, provider, child) {
if (provider.data!.team_uniq_id ==
widget.teamData['team_uniq_id']) {
print("prov $provider.data");
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
// Data table widget in not scrollable so we have to wrap it in a scroll view when we have a large data set..
child: SingleChildScrollView(
child: DataTable(
columns: [
DataColumn(
label: Text('Name'),
tooltip: 'represents if user is verified.'),
DataColumn(
label: Text('Mother_name'),
tooltip: 'represents first S no of the user'),
DataColumn(
label: Text('address'),
tooltip: 'represents Sponsor ID of the user'),
DataColumn(
label: Text('mobile'),
tooltip: 'represents User ID of the user'),
DataColumn(
label: Text('User_s_id'),
tooltip: 'represents Name of the user'),
DataColumn(
label: Text('sponsor_id'),
tooltip: 'represents Mobile of the user'),
DataColumn(
label: Text('email'),
tooltip: 'represents Date of the user'),
DataColumn(
label: Text('city'),
tooltip: 'represents Date of the user'),
DataColumn(
label: Text('state'),
tooltip: 'represents Date of the user'),
DataColumn(
label: Text('dob'),
tooltip: 'represents Date of the user'),
],
rows: provider.data!.user
.map((data) =>
// we return a DataRow every time
DataRow(
// List<DataCell> cells is required in every row
cells: [
red when unverified
DataCell(Text(data.user_name)),
DataCell(Text(data.user_mother_name)),
DataCell(Text(data.user_address)),
DataCell(Text(data.user_mobile)),
DataCell(Text(data.user_sponsor_id)),
DataCell(Text(data.sponsor_id)),
DataCell(Text(data.email)),
DataCell(Text(data.city)),
DataCell(Text(data.state)),
DataCell(Text(data.dob)),
]))
.toList(),
),
),
);
}, provider.getData(context);
return Center(child: CircularProgressIndicator());
),
),
],
),
],
),
);
}
}
this is teamlist api
[
{
"teamType": "direct Team",
"team_uniq_id": "1",
"user": [
{
"user_name": "deepak",
"user_mother_name": "Accomodation",
"user_address": "varanasi",
"user_mobile": "5678989",
"user_sponsor_id": "123456",
"sponsor_id": "3456",
"email": "abc#gmai.com",
"city": "varanasi",
"state": "India",
"dob": "12-5-1996"
},
{
"user_name": "deepak",
"user_mother_name": "Accomodation",
"user_address": "varanasi",
"user_mobile": "5678989",
"user_sponsor_id": "123456",
"sponsor_id": "3456",
"email": "abc#gmai.com",
"city": "varanasi",
"state": "India",
"dob": "12-5-1996"
},
{
"user_name": "deepak",
"user_mother_name": "Accomodation",
"user_address": "varanasi",
"user_mobile": "5678989",
"user_sponsor_id": "123456",
"sponsor_id": "3456",
"email": "abc#gmai.com",
"city": "varanasi",
"state": "India",
"dob": "12-5-1996"
}
]
},
{
"teamType": "left Team",
"team_uniq_id": "2",
"user": [
{
"user_name": "Ashu",
"user_mother_name": "manju",
"user_address": "Mirzapur",
"user_mobile": "222222",
"user_sponsor_id": "123456",
"sponsor_id": "3456",
"email": "abc#gmai.com",
"city": "varanasi",
"state": "India",
"dob": "12-5-1996"
},
{
"user_name": "Ashutodh",
"user_mother_name": "manju1",
"user_address": "Mirzapur1",
"user_mobile": "2222221",
"user_sponsor_id": "1234561",
"sponsor_id": "34561",
"email": "abc#gmai.com1",
"city": "varanasi1",
"state": "India1",
"dob": "12-5-19961"
}
]
},
{
"teamType": "Right Team",
"team_uniq_id": "3",
"user": [
{
"user_name": "tosh",
"user_mother_name": "snju",
"user_address": "Allahabad",
"user_mobile": "44444444",
"user_sponsor_id": "333456",
"sponsor_id": "6666666",
"email": "jkl#gmai.com",
"city": "lucknow",
"state": "India",
"dob": "15-3-1956"
}
]
},
{
"teamType": "Total Team",
"team_uniq_id": "4",
"user": [
{
"user_name": "tosh",
"user_mother_name": "snju",
"user_address": "Allahabad",
"user_mobile": "44444444",
"user_sponsor_id": "333456",
"sponsor_id": "6666666",
"email": "jkl#gmai.com",
"city": "lucknow",
"state": "India",
"dob": "15-3-1956"
},
{
"user_name": "deepak",
"user_mother_name": "Accomodation",
"user_address": "varanasi",
"user_mobile": "5678989",
"user_sponsor_id": "123456",
"sponsor_id": "3456",
"email": "abc#gmai.com",
"city": "varanasi",
"state": "India",
"dob": "12-5-1996"
},
{
"user_name": "deepak",
"user_mother_name": "Accomodation",
"user_address": "varanasi",
"user_mobile": "5678989",
"user_sponsor_id": "123456",
"sponsor_id": "3456",
"email": "abc#gmai.com",
"city": "varanasi",
"state": "India",
"dob": "12-5-1996"
},
{
"user_name": "tosh",
"user_mother_name": "snju",
"user_address": "Allahabad",
"user_mobile": "44444444",
"user_sponsor_id": "333456",
"sponsor_id": "6666666",
"email": "jkl#gmai.com",
"city": "lucknow",
"state": "India",
"dob": "15-3-1956"
}
]
}
]
I feel some error is coming.
You can try to make sure you convert the object you are getting from the server to list, to be able to pass in the list into the widget

flutter how to update grid view

i have grid view shows all data in list and i have drop down with values like price from low to high and when user select any value then i will re-sort the list at this point all is work correctly and list updated but grid view stell with old list.
i cannot update grid view
class ProductsListState extends State<ProductsList> {
double width;
String _title;
String _selectedSort;
String _language;
ProductsListState(this._title);
List productsList;
int filter;
#override
Widget build(BuildContext context) {
MediaQueryData deviceInfo = MediaQuery.of(context);
width = deviceInfo.size.width;
_language = _language ?? AppLocalizations.of(context).tr('lang');
filter = filter ?? 1;
_selectedSort ??= getSortFilter(_language)[0];
productsList = (productsList ?? getProductsList(filter));
print(productsList);
print(filter);
var size = MediaQuery.of(context).size;
var data = EasyLocalizationProvider.of(context).data;
return EasyLocalizationProvider(
data: data,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Color.fromRGBO(205, 14, 64, 1),
appBar:
MarketinoAppBar(title: _title, width: width, appContext: context),
body: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
blurRadius: 13.0,
color: Colors.black.withOpacity(.5),
offset: Offset(6.0, 7.0),
),
],
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20)),
),
),
Column(
children: <Widget>[
Padding(
padding: EdgeInsetsDirectional.fromSTEB(0, 0, 20, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text('SORT BY: '),
DropdownButton<String>(
value: _selectedSort,
onChanged: (value) {
setState(() {
productsList.sort(
(a, b) => a['price'].compareTo(b['price']));
_selectedSort = value;
filter = 2;
});
},
items: getSortFilter(_language).map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
],
),
),
Container(
child: filter == 1
? Grid(productsList, width, size)
: Grid(getProductsList(2), width, size),
)
],
)
],
),
),
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
EasylocaLizationDelegate(locale: data.locale, path: "assets/language")
],
supportedLocales: [Locale('en', 'US'), Locale('ar', 'SA')],
locale: data.savedLocale,
),
);
}
//replace by json
List getProductsList(int filter) {
List list = [];
list.add({
"id": "1",
"name": "sssss",
"imageUrl": "assets/images/Frozen Food.jpg",
"description": "qwerfghjhgfdsaasdfghnjmhgfdsa",
"price": "110",
"quantity": "1",
"isLiked": "false",
"max": "5"
});
list.add({
"id": "2",
"name": "sssss",
"imageUrl": "assets/images/Frozen Food.jpg",
"description": "qwerfghjhgfdsaasdfghnjmhgfdsa",
"price": "112",
"quantity": "1",
"isLiked": "true",
"max": "5"
});
list.add({
"id": "3",
"name": "sssss",
"imageUrl": "assets/images/Frozen Food.jpg",
"description": "qwerfghjhgfdsaasdfghnjmhgfdsa",
"price": "114",
"quantity": "1",
"isLiked": "true",
"max": "10"
});
list.add({
"id": "4",
"name": "sssssssssssssssssssssssssssssssssssssssssssssssssssssssszzzzz",
"imageUrl": "assets/images/Frozen Food.jpg",
"description": "qwerfghjhgfdsaasdfghnjmhgfdsa",
"price": "11",
"quantity": "1",
"isLiked": "false",
"max": "1"
});
list.add({
"id": "5",
"name": "sssss",
"imageUrl": "assets/images/Frozen Food.jpg",
"description": "qwerfghjhgfdsaasdfghnjmhgfdsa",
"price": "110",
"quantity": "1",
"isLiked": "false",
"max": "15"
});
switch (filter) {
case 1:
list.sort((a, b) => a['id'].compareTo(b['id']));
break;
case 2:
list.sort((a, b) => a['price'].compareTo(b['price']));
break;
}
return list;
}
List<String> getSortFilter(String language) {
if (language == 'english')
return [
"الأكثر رواجا",
"السعر من الأقل للأعلى",
"السعر من الأعلى للأقل",
"التخفيضات",
];
else
return [
"Popularty",
"Price: Low to High",
"Price: High to Low",
"Discount",
];
}
}
class Grid extends StatefulWidget {
List productsList;
var _width;
var _size;
Grid(this.productsList, this._width, this._size);
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return GridState(productsList, _width, _size);
}
}
class GridState extends State<Grid> {
List productsList;
var _width;
var _size;
GridState(this.productsList, this._width, this._size);
#override
Widget build(BuildContext context) {
// TODO: implement build
return Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: new GridView.builder(
itemCount: productsList.length,
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: _width > 600 ? 3 : 2,
childAspectRatio: _width > 600 ? 0.6 : _width > 400 ? .725 : .685,
// childAspectRatio: (_itemWidth / _itemHeight),
),
itemBuilder: (BuildContext context, int index) {
return ProductGridTile(
price: double.parse(productsList[index]['price']),
width: _size.width,
image: productsList[index]['imageUrl'],
title: productsList[index]['name'],
likeStatus: productsList[index]['isLiked'] == 'true',
max: double.parse(productsList[index]['max']),
id: int.parse(productsList[index]['id']));
}),
),
);
}
}
gridview updated after re-sort list
You are doing some operations inside the build() method, when you call setState() these operations would be called again. Check that part and also try to update the list this way:
productsList = List.from(productsList)..sort(
(a, b) => a['price'].compareTo(b['price']));