How to populating 2nd DropdownMenu based on first item selected flutter - flutter

I'm populating states name from JSON and display as a dropdown list after that I show 2nd dropdown list based on first value selected. But I don't now how to populate 2nd dropdown when 1st dropdown value changed. I also want to get location id, name and city when select 2nd dropdown value.
My Json
{
"data": [
{
"state": "TEXAS",
"locations": [
{
"id": 1,
"name": "FITT Sugarland",
"city": "HOUSTON",
"state": "TEXAS",
"timezone": "",
"ownerName": "",
"ownerPhoneNumber": "",
"ownerEmail": "",
"ownerWebsite": "",
"capacity": 0,
"description": "HOUSTON SUGARLAND",
"createdBy": "",
"modifiedBy": "",
"createdAt": "2020-08-18T10:17:55.000Z",
"modifiedAt": "2020-08-18T10:17:55.000Z"
},
{
"id": 2,
"name": "FITT Pearland",
"city": "HOUSTON",
"state": "TEXAS",
"timezone": "",
"ownerName": "",
"ownerPhoneNumber": "",
"ownerEmail": "",
"ownerWebsite": "",
"capacity": 0,
"description": "second location",
"createdBy": "",
"modifiedBy": "",
"createdAt": "2020-08-18T10:18:38.000Z",
"modifiedAt": "2020-08-18T10:18:38.000Z"
}
]
}
]
}
Model Class
class LocationModel {
List<LocationList> data;
LocationModel({this.data});
LocationModel.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = new List<LocationList>();
json['data'].forEach((v) {
data.add(new LocationList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class LocationList {
String state;
List<Locations> locations;
LocationList({this.state, this.locations});
LocationList.fromJson(Map<String, dynamic> json) {
state = json['state'];
if (json['locations'] != null) {
locations = new List<Locations>();
json['locations'].forEach((v) {
locations.add(new Locations.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['state'] = this.state;
if (this.locations != null) {
data['locations'] = this.locations.map((v) => v.toJson()).toList();
}
return data;
}
}
class Locations {
int id;
String name;
String city;
String state;
String timezone;
String ownerName;
String ownerPhoneNumber;
String ownerEmail;
String ownerWebsite;
int capacity;
String description;
String createdBy;
String modifiedBy;
String createdAt;
String modifiedAt;
Locations(
{this.id,
this.name,
this.city,
this.state,
this.timezone,
this.ownerName,
this.ownerPhoneNumber,
this.ownerEmail,
this.ownerWebsite,
this.capacity,
this.description,
this.createdBy,
this.modifiedBy,
this.createdAt,
this.modifiedAt});
Locations.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
city = json['city'];
state = json['state'];
timezone = json['timezone'];
ownerName = json['ownerName'];
ownerPhoneNumber = json['ownerPhoneNumber'];
ownerEmail = json['ownerEmail'];
ownerWebsite = json['ownerWebsite'];
capacity = json['capacity'];
description = json['description'];
createdBy = json['createdBy'];
modifiedBy = json['modifiedBy'];
createdAt = json['createdAt'];
modifiedAt = json['modifiedAt'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['city'] = this.city;
data['state'] = this.state;
data['timezone'] = this.timezone;
data['ownerName'] = this.ownerName;
data['ownerPhoneNumber'] = this.ownerPhoneNumber;
data['ownerEmail'] = this.ownerEmail;
data['ownerWebsite'] = this.ownerWebsite;
data['capacity'] = this.capacity;
data['description'] = this.description;
data['createdBy'] = this.createdBy;
data['modifiedBy'] = this.modifiedBy;
data['createdAt'] = this.createdAt;
data['modifiedAt'] = this.modifiedAt;
return data;
}
}
My Code
import 'dart:io';
import 'package:fittheorem/models/location_list.dart';
import 'package:fittheorem/providers/auth_session.dart';
import 'package:fittheorem/providers/user_details.dart';
import 'package:fittheorem/ui/widgets/error_snakbar.dart';
import 'package:fittheorem/utils/app_config.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
class LocationUpdate extends StatefulWidget {
#override
_LocationUpdateState createState() => _LocationUpdateState();
}
class _LocationUpdateState extends State<LocationUpdate> {
LocationModel _locationModel;
bool isLoading = true;
String _selectedState = "TEXAS";
List<String> _statesList = [];
String _selectedLocation = "FITT Sugarland";
List<Locations> _locationsList = List();
#override
void initState() {
// TODO: implement initState
super.initState();
getList();
}
Future<void> getList() async {
try {
_locationModel = await Provider.of<UserDetails>(context, listen: false)
.getLocationList("token");
for (int i = 0; i < _locationModel.data.length; i++) {
_statesList.add(_locationModel.data[i].state);
}
_locationsList = _locationModel.data[0].locations;
_selectedState = _statesList[0];
_selectedLocation = _locationsList[0].name;
if (mounted) {
setState(() {
isLoading = false;
});
}
} on HttpException catch (error) {
CustomWidgets.buildErrorSnackbar(context);
} catch (error) {
CustomWidgets.buildErrorSnackbar(context);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: AppConfig.bgColor,
child: SafeArea(
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
height: 40.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
Navigator.pop(context, true);
},
child: Container(
height: 25.0,
width: 25.0,
child: SvgPicture.asset(AppConfig.backImage,
color: Colors.white, semanticsLabel: 'back')),
),
Text('LOCATION',
style: GoogleFonts.roboto(
textStyle: TextStyle(
fontSize: 18.0, color: Color(0xffFFFFFF)),
)),
SizedBox(
width: 25.0,
),
],
),
),
Expanded(
child: Container(
color: Colors.white,
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.all(30.0),
child: isLoading
? Center(
child: AppConfig().myLoader(),
)
: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.only(left: 5.0),
child: Text('UPDATE YOUR LOCATION',
style: GoogleFonts.roboto(
textStyle: TextStyle(
fontSize: 16.0,
color: Color(0xff000000)),
)),
),
SizedBox(
height: 20.0,
),
Container(
height: 40.0,
decoration: new BoxDecoration(
border: new Border.all(
color: Colors.black54, width: 0.0),
borderRadius: new BorderRadius.circular(10.0),
),
child: new DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: new DropdownButton(
value: _selectedState,
hint: Text("State"),
isExpanded: true,
items: _statesList
.map((String item) =>
DropdownMenuItem<String>(
child: Text(item),
value: item))
.toList(),
onChanged: (String newValue) {
if (mounted)
setState(() {
_selectedState = newValue;
});
},
style: Theme.of(context)
.textTheme
.bodyText2,
))),
),
SizedBox(
height: 20.0,
),
Container(
height: 40.0,
decoration: new BoxDecoration(
border: new Border.all(
color: Colors.black54, width: 0.0),
borderRadius: new BorderRadius.circular(10.0),
),
child: new DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: new DropdownButton(
value: _selectedLocation,
hint: Text("Location"),
isExpanded: true,
items: _locationsList.map((item) {
return new DropdownMenuItem(
child: new Text(item.name),
value: item.name,
);
}).toList(),
onChanged: (newValue) {
if (mounted) print(newValue);
setState(() {
_selectedLocation = newValue;
});
},
style: Theme.of(context)
.textTheme
.bodyText2,
))),
)
],
),
),
)
],
),
),
),
);
}
}

You can copy paste run full code below
Step 1: Change data type of _selectedLocation
Locations _selectedLocation;
Step 2: _selectedState's onChanged
onChanged: (String Value) {
if (mounted)
setState(() {
_selectedState = Value;
int index = _locationModel.data
.indexWhere((element) =>
element.state ==
_selectedState);
_locationsList = _locationModel
.data[index].locations;
_selectedLocation =
_locationsList[0];
});
},
Step 3: _selectedLocation's onChanged
onChanged: (Value) {
if (mounted) print(Value);
setState(() {
_selectedLocation = Value;
print(
"${_selectedLocation.name} ${_selectedLocation.id} ${_selectedLocation.city}");
});
},
working demo
full code
import 'dart:convert';
import 'package:flutter/material.dart';
LocationModel locationModelFromJson(String str) =>
LocationModel.fromJson(json.decode(str));
class LocationModel {
List<LocationList> data;
LocationModel({this.data});
LocationModel.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = List<LocationList>();
json['data'].forEach((v) {
data.add(LocationList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class LocationList {
String state;
List<Locations> locations;
LocationList({this.state, this.locations});
LocationList.fromJson(Map<String, dynamic> json) {
state = json['state'];
if (json['locations'] != null) {
locations = List<Locations>();
json['locations'].forEach((v) {
locations.add(Locations.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['state'] = this.state;
if (this.locations != null) {
data['locations'] = this.locations.map((v) => v.toJson()).toList();
}
return data;
}
}
class Locations {
int id;
String name;
String city;
String state;
String timezone;
String ownerName;
String ownerPhoneNumber;
String ownerEmail;
String ownerWebsite;
int capacity;
String description;
String createdBy;
String modifiedBy;
String createdAt;
String modifiedAt;
Locations(
{this.id,
this.name,
this.city,
this.state,
this.timezone,
this.ownerName,
this.ownerPhoneNumber,
this.ownerEmail,
this.ownerWebsite,
this.capacity,
this.description,
this.createdBy,
this.modifiedBy,
this.createdAt,
this.modifiedAt});
Locations.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
city = json['city'];
state = json['state'];
timezone = json['timezone'];
ownerName = json['ownerName'];
ownerPhoneNumber = json['ownerPhoneNumber'];
ownerEmail = json['ownerEmail'];
ownerWebsite = json['ownerWebsite'];
capacity = json['capacity'];
description = json['description'];
createdBy = json['createdBy'];
modifiedBy = json['modifiedBy'];
createdAt = json['createdAt'];
modifiedAt = json['modifiedAt'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['city'] = this.city;
data['state'] = this.state;
data['timezone'] = this.timezone;
data['ownerName'] = this.ownerName;
data['ownerPhoneNumber'] = this.ownerPhoneNumber;
data['ownerEmail'] = this.ownerEmail;
data['ownerWebsite'] = this.ownerWebsite;
data['capacity'] = this.capacity;
data['description'] = this.description;
data['createdBy'] = this.createdBy;
data['modifiedBy'] = this.modifiedBy;
data['createdAt'] = this.createdAt;
data['modifiedAt'] = this.modifiedAt;
return data;
}
}
class LocationUpdate extends StatefulWidget {
#override
_LocationUpdateState createState() => _LocationUpdateState();
}
class _LocationUpdateState extends State<LocationUpdate> {
LocationModel _locationModel;
bool isLoading = true;
String _selectedState = "TEXAS";
List<String> _statesList = [];
Locations _selectedLocation;
List<Locations> _locationsList = List();
#override
void initState() {
// TODO: implement initState
super.initState();
getList();
}
Future<void> getList() async {
try {
/*_locationModel = await Provider.of<UserDetails>(context, listen: false)
.getLocationList("token");*/
String jsonString = '''
{
"data": [
{
"state": "TEXAS",
"locations": [
{
"id": 1,
"name": "FITT Sugarland",
"city": "HOUSTON",
"state": "TEXAS",
"timezone": "",
"ownerName": "",
"ownerPhoneNumber": "",
"ownerEmail": "",
"ownerWebsite": "",
"capacity": 0,
"description": "HOUSTON SUGARLAND",
"createdBy": "",
"modifiedBy": "",
"createdAt": "2020-08-18T10:17:55.000Z",
"modifiedAt": "2020-08-18T10:17:55.000Z"
},
{
"id": 2,
"name": "FITT Pearland",
"city": "HOUSTON",
"state": "TEXAS",
"timezone": "",
"ownerName": "",
"ownerPhoneNumber": "",
"ownerEmail": "",
"ownerWebsite": "",
"capacity": 0,
"description": "second location",
"createdBy": "",
"modifiedBy": "",
"createdAt": "2020-08-18T10:18:38.000Z",
"modifiedAt": "2020-08-18T10:18:38.000Z"
}
]
},
{
"state": "A",
"locations": [
{
"id": 1,
"name": "A1",
"city": "A City 1",
"state": "A",
"timezone": "",
"ownerName": "",
"ownerPhoneNumber": "",
"ownerEmail": "",
"ownerWebsite": "",
"capacity": 0,
"description": "HOUSTON SUGARLAND",
"createdBy": "",
"modifiedBy": "",
"createdAt": "2020-08-18T10:17:55.000Z",
"modifiedAt": "2020-08-18T10:17:55.000Z"
},
{
"id": 2,
"name": "A2",
"city": "A city 2",
"state": "A",
"timezone": "",
"ownerName": "",
"ownerPhoneNumber": "",
"ownerEmail": "",
"ownerWebsite": "",
"capacity": 0,
"description": "second location",
"createdBy": "",
"modifiedBy": "",
"createdAt": "2020-08-18T10:18:38.000Z",
"modifiedAt": "2020-08-18T10:18:38.000Z"
}
]
}
]
}
''';
_locationModel = locationModelFromJson(jsonString);
for (int i = 0; i < _locationModel.data.length; i++) {
_statesList.add(_locationModel.data[i].state);
}
_locationsList = _locationModel.data[0].locations;
_selectedState = _statesList[0];
_selectedLocation = _locationsList[0];
if (mounted) {
setState(() {
isLoading = false;
});
}
//} on HttpException catch (error) {
// CustomWidgets.buildErrorSnackbar(context);
} catch (error) {
//CustomWidgets.buildErrorSnackbar(context);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
//color: AppConfig.bgColor,
child: SafeArea(
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
height: 40.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
Navigator.pop(context, true);
},
child: Container(
height: 25.0,
width: 25.0,
child: Image.network(
'https://picsum.photos/250?image=9',
color: Colors.white)),
),
Text('LOCATION',
style: TextStyle(
fontSize: 18.0,
color: Color(0xffFFFFFF),
)),
SizedBox(
width: 25.0,
),
],
),
),
Expanded(
child: Container(
color: Colors.white,
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.all(30.0),
child: isLoading
? Center(
child: CircularProgressIndicator(),
)
: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.only(left: 5.0),
child: Text('UPDATE YOUR LOCATION',
style: TextStyle(
fontSize: 16.0,
color: Color(0xff000000),
)),
),
SizedBox(
height: 20.0,
),
Container(
height: 40.0,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black54, width: 0.0),
borderRadius: BorderRadius.circular(10.0),
),
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton(
value: _selectedState,
hint: Text("State"),
isExpanded: true,
items: _statesList
.map((String item) =>
DropdownMenuItem<String>(
child: Text(item),
value: item))
.toList(),
onChanged: (String Value) {
if (mounted)
setState(() {
_selectedState = Value;
int index = _locationModel.data
.indexWhere((element) =>
element.state ==
_selectedState);
_locationsList = _locationModel
.data[index].locations;
_selectedLocation =
_locationsList[0];
});
},
style: Theme.of(context)
.textTheme
.bodyText2,
))),
),
SizedBox(
height: 20.0,
),
Container(
height: 40.0,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black54, width: 0.0),
borderRadius: BorderRadius.circular(10.0),
),
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton(
value: _selectedLocation,
hint: Text("Location"),
isExpanded: true,
items: _locationsList.map((item) {
return DropdownMenuItem(
child: Text(item.name),
value: item,
);
}).toList(),
onChanged: (Value) {
if (mounted) print(Value);
setState(() {
_selectedLocation = Value;
print(
"${_selectedLocation.name} ${_selectedLocation.id} ${_selectedLocation.city}");
});
},
style: Theme.of(context)
.textTheme
.bodyText2,
))),
)
],
),
),
)
],
),
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: LocationUpdate(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Related

Flutter : How to display sername,pname data from a model class(PokelistModel)?

I have created a PokelistModel class and I want to display data in ServiceRequestedPage. But I am unable to access sername,pname from the model class to display in ServiceRequestedPage.
API Responses:-
{
"service": [
{
"id": "444",
"user_id": "34856",
"service_provider_id": "289",
"address": "235, AH45, Doordarshan Colony, Gajapati Nagar, Bhubaneswar, Odisha 751013, India",
"date": "2022-03-28",
"entry_time": "2022-03-28 12:16:14",
"sername": "Barber",
"pname": "Sabita Panda",
"emaildta": "",
"paddress": "Bhubaneswar, Odisha, India",
"serphone": "9853575231",
"serimage": "default.png",
"review": [],
"total_rating": 0
},
{
"id": "441",
"user_id": "34856",
"service_provider_id": "287",
"address": "235, AH45, Doordarshan Colony, Gajapati Nagar, Bhubaneswar, Odisha 751013, India",
"date": "2022-02-02",
"entry_time": "2022-02-02 16:03:11",
"sername": "Aaya & Maid ",
"pname": "Rabi Panda",
"emaildta": "",
"paddress": " Bhubaneswar, Odisha, India",
"serphone": "9853578231",
"serimage": "default.png",
"review": [
{
"id": "41",
"user_id": "34856",
"service_provider_id": "287",
"total_rating": "5.00",
"review": "g",
"entry_time": "2022-03-22 16:45:41"
},
{
"id": "42",
"user_id": "34856",
"service_provider_id": "287",
"total_rating": "5.00",
"review": "nyc",
"entry_time": "2022-03-23 16:32:33"
}
],
"total_rating": 5
},
{
"id": "431",
"user_id": "34856",
"service_provider_id": "2722",
"address": "214, Acharya Vihar, Bhubaneswar, Odisha 751013, India",
"date": "2021-02-19",
"entry_time": "2021-02-19 22:05:09",
"sername": "Hair & Spa",
"pname": "Friends Hairstyle",
"emaildta": "",
"paddress": "Plot No-88/6, Jaydev Vhir Over Bridge, Acharya Vihar, Bhubaneshwar - 751013, Near Trupati Kalyani Mandap",
"serphone": "9090531519",
"serimage": "",
"review": [
{
"id": "37",
"user_id": "34856",
"service_provider_id": "2722",
"total_rating": "5.00",
"review": "super",
"entry_time": "2021-10-20 12:11:00"
},
{
"id": "38",
"user_id": "34856",
"service_provider_id": "2722",
"total_rating": "5.00",
"review": "super",
"entry_time": "2021-10-20 12:11:02"
},
{
"id": "43",
"user_id": "34856",
"service_provider_id": "2722",
"total_rating": "5.00",
"review": "superb ",
"entry_time": "2022-03-23 16:33:00"
}
],
"total_rating": 5
}
],
"status": 1,
"message": "3 Matches Found!",
"total_review": 3
}
PokelistModel:-
import 'dart:convert';
PokelistModel pokelistModelFromJson(String str) => PokelistModel.fromJson(json.decode(str));
String pokelistModelToJson(PokelistModel data) => json.encode(data.toJson());
class PokelistModel {
PokelistModel({
required this.service,
required this.status,
required this.message,
required this.totalReview,
});
List<Service> service;
int status;
String message;
int totalReview;
factory PokelistModel.fromJson(Map<String, dynamic> json) => PokelistModel(
service: List<Service>.from(json["service"].map((x) => Service.fromJson(x))),
status: json["status"],
message: json["message"],
totalReview: json["total_review"],
);
Map<String, dynamic> toJson() => {
"service": List<dynamic>.from(service.map((x) => x.toJson())),
"status": status,
"message": message,
"total_review": totalReview,
};
}
class Service {
Service({
required this.id,
required this.userId,
required this.serviceProviderId,
required this.address,
required this.date,
required this.entryTime,
required this.sername,
required this.pname,
required this.emaildta,
required this.paddress,
required this.serphone,
required this.serimage,
required this.review,
required this.totalRating,
});
String id;
String userId;
String serviceProviderId;
String address;
DateTime date;
DateTime entryTime;
String sername;
String pname;
String emaildta;
String paddress;
String serphone;
String serimage;
List<Review> review;
int totalRating;
factory Service.fromJson(Map<String, dynamic> json) => Service(
id: json["id"],
userId: json["user_id"],
serviceProviderId: json["service_provider_id"],
address: json["address"],
date: DateTime.parse(json["date"]),
entryTime: DateTime.parse(json["entry_time"]),
sername: json["sername"],
pname: json["pname"],
emaildta: json["emaildta"],
paddress: json["paddress"],
serphone: json["serphone"],
serimage: json["serimage"],
review: List<Review>.from(json["review"].map((x) => Review.fromJson(x))),
totalRating: json["total_rating"],
);
Map<String, dynamic> toJson() => {
"id": id,
"user_id": userId,
"service_provider_id": serviceProviderId,
"address": address,
"date": "${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}",
"entry_time": entryTime.toIso8601String(),
"sername": sername,
"pname": pname,
"emaildta": emaildta,
"paddress": paddress,
"serphone": serphone,
"serimage": serimage,
"review": List<dynamic>.from(review.map((x) => x.toJson())),
"total_rating": totalRating,
};
}
class Review {
Review({
required this.id,
required this.userId,
required this.serviceProviderId,
required this.totalRating,
required this.review,
required this.entryTime,
});
String id;
String userId;
String serviceProviderId;
String totalRating;
String review;
DateTime entryTime;
factory Review.fromJson(Map<String, dynamic> json) => Review(
id: json["id"],
userId: json["user_id"],
serviceProviderId: json["service_provider_id"],
totalRating: json["total_rating"],
review: json["review"],
entryTime: DateTime.parse(json["entry_time"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"user_id": userId,
"service_provider_id": serviceProviderId,
"total_rating": totalRating,
"review": review,
"entry_time": entryTime.toIso8601String(),
};
}
ServiceRequestedPage :-
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:http/http.dart';
import 'package:newbharatbiz/Model%20Class/PokelistService.dart';
import 'package:newbharatbiz/Model%20Class/pokelist_model.dart';
import 'package:newbharatbiz/Screens/AddReviewPage.dart';
import 'package:newbharatbiz/Screens/RequestedServiceDetailsPage.dart';
import 'HomePage.dart';
import 'package:http/http.dart' as http;
class ServiceRequestedPage extends StatefulWidget {
#override
_YourWidgetState createState() => _YourWidgetState();
}
class _YourWidgetState extends State<ServiceRequestedPage> {
bool isLoading = false;
late Future<PokelistModel> pokelist;
#override
void initState() {
super.initState();
pokelist = PokelistService.getProducts();
}
Future delete_poke() async {
final String DeletePokeAPI =
"https://newbharatbiz.in/mobile_api/v4/delete_poke.php";
setState(() {
isLoading = true;
});
final headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
"Content-Type": "application/x-www-form-urlencoded"
};
final Map<String, dynamic> body = {
"id": "idd",
};
String encodedBody = body.keys.map((key) => "$key=${body[key]}").join("&");
//var jsonBody = json.encode(body);
Response response = await http.post(Uri.parse(DeletePokeAPI),
body: encodedBody, headers: headers);
var jsonResponse = jsonDecode(response.body);
print(jsonResponse);
if (response.statusCode == 200) {
setState(() {
isLoading = false;
});
// If the server did return a 201 CREATED response,
// then parse the JSON.
//return json.decode(response.body)['services'];
print(response);
// return CatwiseServiceModel.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 201 CREATED response,
// then throw an exception.
throw Exception('Failed to load.');
}
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => true,
child: Scaffold(
appBar: new AppBar(
title: new Text('Service Requested List'),
leading: new IconButton(
icon: new Icon(Icons.arrow_back_outlined),
onPressed: () {
Navigator.pop(
context, true); // It worked for me instead of above line
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
}),
),
body: SingleChildScrollView(
child:
Column(mainAxisAlignment: MainAxisAlignment.start, children: [
FutureBuilder<PokelistModel>(
future: pokelist,
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
//print(idd(snapshot.data[0]));
return SingleChildScrollView(
child: Column(
children: <Widget>[
ListView.builder(
padding: EdgeInsets.zero,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (BuildContext context, int index) {
return Container(
margin: EdgeInsets.zero,
child: Card(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
ListTile(
leading: CircleAvatar(
child: Image.asset(
"assets/dummyprofile.png",
fit: BoxFit.fill),
backgroundColor:
Colors.transparent,
),
title: Text(
sername(snapshot.data[index]),
style: TextStyle(
color: Colors.black87,
fontWeight:
FontWeight.bold,
fontSize: 16),
),
/*subtitle: Row(
children: <Widget>[
Text("M/S : ",
style: TextStyle(
color: Colors.black87,
fontWeight: FontWeight.bold,
fontSize: 13)),
Text(pname(snapshot.data[index]),
style: TextStyle(
color: Colors.black87)),
],
),*/
subtitle: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
"M/S : " +
pname(snapshot
.data[index]),
style: TextStyle(
color: Colors.black,
fontSize: 14)),
SizedBox(height: 5),
Text(
"Phone No : " +
serphone(snapshot
.data[index]),
style: TextStyle(
color: Colors.black,
fontSize: 14)),
],
),
trailing: new IconButton(
icon: new Icon(Icons.close,
color: Colors.black87,
size: 30.0),
onPressed: () {
delete_poke();
},
)),
SizedBox(height: 10),
Padding(
padding: const EdgeInsets.only(
left: 10.0),
child: Text(
"Address : " +
paddress(
snapshot.data[index]),
style: TextStyle(
color: Colors.black,
fontSize: 14)),
),
SizedBox(height: 15),
Padding(
padding: const EdgeInsets.only(
left: 10.0, bottom: 10.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
SizedBox(
height: 30.0,
child: MaterialButton(
child: Text("Rating"),
textColor: Colors.white,
color: Color(0xFF00796B),
disabledColor:
Colors.blue,
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius.all(
Radius.circular(
10.0), // Change your border radius here
),
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
AddReviewPage(
sername: snapshot
.data[
index]
['sername'],
pname: snapshot
.data[
index]
['pname'],
),
),
);
},
),
),
SizedBox(width: 20),
SizedBox(
height: 30.0,
child: MaterialButton(
child: Text("View"),
textColor: Colors.white,
color: Color(0xFF00796B),
disabledColor:
Colors.blue,
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius.all(
Radius.circular(
10.0), // Change your border radius here
),
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
RequestedServiceDetailsPage(
sername: snapshot
.data[
index]
['sername'],
pname: snapshot
.data[
index]
['pname'],
paddress: snapshot
.data[
index][
'paddress'],
serphone: snapshot
.data[
index][
'serphone'],
),
),
);
},
),
),
// SizedBox(height: 10),
/* Button (),
RatingBar (),
Button ()*/
]),
)
])));
})
],
),
);
}
return const Center(
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
),
);
}
// By default, show a loading spinner.
),
Visibility(visible: isLoading, child: CircularProgressIndicator())
]),
)),
);
}
}
PokelistService:-
import 'dart:convert';
import 'package:http/http.dart';
import 'package:newbharatbiz/Model%20Class/pokelist_model.dart';
import 'package:http/http.dart' as http;
class PokelistService {
static Future<PokelistModel> getProducts() async {
final String ServiceAPI =
"https://newbharatbiz.in/mobile_api/v4/listing_poke.php";
final headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
"Content-Type": "application/x-www-form-urlencoded"
};
final Map<String, dynamic> body = {
"user_id": "34856",
};
String encodedBody = body.keys.map((key) => "$key=${body[key]}").join("&");
//var jsonBody = json.encode(body);
Response response = await http.post(Uri.parse(ServiceAPI),
body: encodedBody, headers: headers);
var jsonResponse = jsonDecode(response.body);
print(jsonResponse);
if (response.statusCode == 200) {
// If the server did return a 201 CREATED response,
// then parse the JSON.
//return json.decode(response.body)['services'];
print(json.decode(response.body));;
final body = json.decode(response.body);
return body.map(PokelistModel.fromJson);
// var data = json.decode(response.body)
// return CatwiseServiceModel.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 201 CREATED response,
// then throw an exception.
throw Exception('Failed to load.');
}
}
}
There are a few ways how to do it. You can try this one:
Change response model to incorporate all the data. Just copy and paste JSON that you received here: https://app.quicktype.io
Then change the part here:
Text(
snapshot.data[index].service.sername,
style: TextStyle(color: Colors.black87,
fontWeight: FontWeight.bold,
fontSize: 16),
),
Use the same structure for any other data that you need. Maybe you could create more generic ApiService and pass the necessary variables as parameters, like this:
Future<ApiResponse?> post(String url, dynamic body,
{Map<String, String>? headers}) async {
print('API Post: ${this.url+url}');
try {
final response = await http.post(Uri.parse(this.url+url),
body: body,
headers: headers
);
if (response.statusCode == 200) {
String data = response.body;
final decodedData = jsonDecode(data);
print('API Post: $decodedData)');
final _apiResponse = ApiResponse.fromJson(decodedData);
return _apiResponse;
}
} catch(e) {
print('API Post: $e');
}
return null;
}
I accessed the array like this> List data = snapshot.data!.service; then will displaylike this> sername data[index].sername
List data = snapshot.data!.service;
sername data[index].sername

Flutter failed to post data to create user with API

I try to create user using api but it throws an exception when executed.
So, here is my json response as below.
{
"success": 1,
"user": {
"user_id": "612f02fc4ae19",
"name": "Test User3",
"mobile": "8347406873",
"email": "dhaval#gmail.com",
"standard_id": "5d1594e283e1a",
"medium_id": "5d15938aa1344",
"location": "Vyara",
"created_at": "2021-09-01"
},
"msg": "Your account has been created successfully."
}
As response i created model class as below in signup_model.dart file.
import 'dart:convert';
SignupModel signupModelFromJson(String str) =>
SignupModel.fromJson(json.decode(str));
String signupModelToJson(SignupModel data) => json.encode(data.toJson());
class SignupModel {
SignupModel({
this.success,
this.user,
this.msg,
});
int? success;
UserRegistration? user;
String? msg;
factory SignupModel.fromJson(Map<String, dynamic> json) => SignupModel(
success: json["success"],
user: UserRegistration.fromJson(json["user"]),
msg: json["msg"],
);
Map<String, dynamic> toJson() => {
"success": success,
"user": user?.toJson(),
"msg": msg,
};
}
class UserRegistration {
UserRegistration({
this.userId,
this.name,
this.mobile,
this.email,
this.standardId,
this.mediumId,
this.location,
this.createdAt,
});
String? userId;
String? name;
String? mobile;
String? email;
String? standardId;
String? mediumId;
String? location;
DateTime? createdAt;
factory UserRegistration.fromJson(Map<String, dynamic> json) =>
UserRegistration(
userId: json["user_id"],
name: json["name"],
mobile: json["mobile"],
email: json["email"],
standardId: json["standard_id"],
mediumId: json["medium_id"],
location: json["location"],
createdAt: DateTime.parse(json["created_at"]),
);
Map<String, dynamic> toJson() => {
"user_id": userId,
"name": name,
"mobile": mobile,
"email": email,
"standard_id": standardId,
"medium_id": mediumId,
"location": location,
"created_at":
"${createdAt?.year.toString().padLeft(4, '0')}-${createdAt?.month.toString().padLeft(2, '0')}-${createdAt?.day.toString().padLeft(2, '0')}",
};
}
Function which i created as below in api_manager.dart file.
Future<UserRegistration> createUser(
String name,
String email,
String mobile,
String standardId,
String mediumId,
) async {
final registrationUrl = "$baseUrl/user/register";
final response = await http.post(
Uri.parse(registrationUrl),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'name': name,
'email': email,
'mobile': mobile,
'standard_id': standardId,
'medium_id': mediumId,
}),
);
if (response.statusCode == 200) {
print(response.body);
return UserRegistration.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to create User.');
}
}
And My signup screen Code as below in signup_screen.dart file.
class _SignUp1State extends State<SignUp1> {
final baseUrl = SankalpApi().baseUrl;
bool value = false;
var _standards = <Standard>[];
var _mediums = <Medium>[];
Standard? selectedStandard;
Medium? selectedMedium;
var standardId;
var mediumId;
final TextEditingController _nameController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _mobileController = TextEditingController();
Future<UserRegistration>? userRegistration;
GlobalKey<FormState> _globalFormKey = GlobalKey<FormState>();
bool isApiCallProcess = false;
#override
void initState() {
super.initState();
ApiManager().getStandards().then((standards) {
setState(() {
_standards = standards;
});
});
}
void onMediumChange(standard) {
setState(() {
selectedStandard = standard;
_mediums = [];
});
String mediumUrl =
"$baseUrl/medium/get_by_course_id?standard_id=${selectedStandard?.standardId}";
ApiManager().getMediums(mediumUrl).then((List<Medium> value) => {
setState(() {
_mediums = value;
})
});
}
#override
Widget build(BuildContext context) {
final Shader linearGradient = LinearGradient(
colors: <Color>[
Color(0xff8921aa),
Color(0xffDA44bb),
],
).createShader(new Rect.fromLTWH(0.0, 0.0, 200.0, 70.0));
return SingleChildScrollView(
child: Form(
key: _globalFormKey,
child: Container(
padding: EdgeInsets.all(12),
child: Column(
children: [
SizedBox(height: 30),
Text(
'Learn from wide range of videos and tutorials',
textAlign: TextAlign.center,
style: GoogleFonts.openSans(
fontSize: 15,
color: Colors.grey[600],
),
),
TextFormField(
decoration: InputDecoration(labelText: "Full Name"),
controller: _nameController,
validator: (value) {
if (value!.isEmpty) {
return "Name is required.";
}
return null;
},
onSaved: (value) {
//this.userRegistration.name = value.toString().trim();
},
),
SizedBox(height: 10),
TextFormField(
decoration: InputDecoration(labelText: "Email"),
controller: _emailController,
validator: (value) {
if (value!.isEmpty) {
return 'Email is required.';
}
if (!RegExp("^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+.[a-z]")
.hasMatch(value)) {
return 'Enter valid Email';
}
return null;
},
onSaved: (value) {
//this.userRegistration.email = value.toString().trim();
},
),
SizedBox(height: 10),
TextFormField(
decoration: InputDecoration(labelText: "Mobile Number"),
controller: _mobileController,
validator: (value) {
String pattern = r'(^[0-9]*$)';
RegExp regExp = new RegExp(pattern);
if (value!.length == 0) {
return "Mobile is required";
} else if (value.length != 10) {
return "Mobile number must 10 digits";
} else if (!regExp.hasMatch(value)) {
return "Mobile Number must be digits";
}
return null;
},
onSaved: (value) {
//this.userRegistration.mobile = value.toString().trim();
},
),
SizedBox(height: 20),
DropdownButtonFormField<Standard>(
validator: (value) {
if (value == null) {
return "Select Standard";
}
},
isExpanded: true,
hint: Text('Select Standard'),
value: selectedStandard,
items: _standards.map((Standard standard) {
return DropdownMenuItem<Standard>(
value: standard,
child: Text(standard.standardName),
);
}).toList(),
onSaved: (value) {
selectedStandard = value;
//this.userRegistration.standardId = value!.standardId;
},
onChanged: (val) {
setState(() {
selectedStandard = val;
standardId = val?.standardId;
// print("StandardId : ${val?.standardId}");
// print("StandardId : ${val?.standardName}");
onMediumChange(val);
});
},
),
SizedBox(height: 20),
DropdownButtonFormField<Medium>(
validator: (value) {
if (value == null) {
return "Select Medium";
}
},
isExpanded: true,
hint: Text('Select Medium'),
value: selectedMedium,
items: _mediums.map((Medium medium) {
return DropdownMenuItem<Medium>(
value: medium,
child: Text(medium.mediumName),
);
}).toList(),
onSaved: (value) {
selectedMedium = value;
//this.userRegistration.mediumId = value!.mediumId;
},
onChanged: (val) {
setState(() {
selectedMedium = val;
mediumId = val?.mediumId;
// print("Medium id : ${val?.mediumId}");
// print("Medium id : ${val?.mediumName}");
});
}),
SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ElevatedButton(
onPressed: () {
if (validateAndSave()) {
setState(() {
this.isApiCallProcess = true;
print(_nameController.text);
print(_emailController.text);
print(_mobileController.text);
print(standardId);
print(mediumId);
userRegistration = ApiManager().createUser(
_nameController.text,
_emailController.text,
_mobileController.text,
standardId,
mediumId,
);
});
}
},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25))),
child: Ink(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0xff8921aa),
const Color(0xffDA44bb),
],
),
borderRadius: BorderRadius.circular(25)),
child: Container(
width: 100,
height: 50,
alignment: Alignment.center,
child: Text(
'SIGNUP',
style: TextStyle(
fontSize: 15,
),
),
),
),
),
],
),
SizedBox(
height: 60,
),
Text('Already have an account?'),
TextButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Login2()));
},
child: Text(
'Login',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
foreground: new Paint()..shader = linearGradient,
),
),
)
],
),
),
),
);
}
bool validateAndSave() {
final form = _globalFormKey.currentState;
if (form!.validate()) {
form.save();
return true;
}
return false;
}
}
So, when i try to sign up it thorows an Exception as below.
So what is the problem in given code.?

only single row comes from the json api

I am beginner in flutter ,I used an API of soccer to get some information of player transferts ,so I have created a model class that contains only the information that I need to ,but when I executed, I had this error:
E/flutter ( 5073): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter ( 5073): #0 new Transferts.fromJson (package:tl_fantasy/models/transfert_json.dart:12:26)
E/flutter ( 5073): #1 _PlayerDetailsState.getTeams.<anonymous closure>.<anonymous closure> (package:tl_fantasy/players/player_details.dart:45:45)
So I changed my model class
if i put this in the model class it works when i put it for example json['transfers'][0]['date'], but the problem is it gives me only the first result , what i need is all results, how to replace[0] by a kind of index or something? how to take all elements?
Here the json that i am trying to access:
{
"response": [
{
"player": {
"id": 35845,
"name": "Hernán Darío Burbano"
},
"update": "2020-02-06T00:08:15+00:00",
"transfers": [
{
"date": "2019-07-15",
"type": "Free",
"teams": {
"in": {
"id": 2283,
"name": "Atlas",
"logo": "https://media.api-sports.io/football/teams/2283.png"
}
}
},
{
"date": "2019-01-01",
"type": "N/A",
"teams": {
"in": {
"id": 1937,
"name": "Atletico Atlas",
"logo": "https://media.api-sports.io/football/teams/1937.png"
}
}
}
]
}
]
}
Here my model class tranfert_json:
class Response {
Player player;
String update;
List<Transfers> transfers;
Response({this.player, this.update, this.transfers});
Response.fromJson(Map<String, dynamic> json) {
player = json['player'] != null ? new Player.fromJson(json['player']) : null;
update = json['update'];
if (json['transfers'] != null) {
transfers = new List<Transfers>();
json['transfers'].forEach((v) { transfers.add(new Transfers.fromJson(v)); });
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.player != null) {
data['player'] = this.player.toJson();
}
data['update'] = this.update;
if (this.transfers != null) {
data['transfers'] = this.transfers.map((v) => v.toJson()).toList();
}
return data;
}
}
class Player {
int id;
String name;
Player({this.id, this.name});
Player.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
class Transfers {
String date;
String type;
Teams teams;
Transfers({this.date, this.type, this.teams});
Transfers.fromJson(Map<String, dynamic> json) {
date = json['date'];
type = json['type'];
teams = json['teams'] != null ? new Teams.fromJson(json['teams']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['date'] = this.date;
data['type'] = this.type;
if (this.teams != null) {
data['teams'] = this.teams.toJson();
}
return data;
}
}
class Teams {
In teamIn;
Teams({this.teamIn});
Teams.fromJson(Map<String, dynamic> json) {
teamIn = json['in'] != null ? new In.fromJson(json['in']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.teamIn != null) {
data['in'] = this.teamIn.toJson();
}
return data;
}
}
class In {
int id;
String name;
String logo;
In({this.id, this.name, this.logo});
In.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
logo = json['logo'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['logo'] = this.logo;
return data;
}
}
Here my player_details class:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:tl_fantasy/models/transfert_json.dart';
class PlayerDetails extends StatefulWidget {
int id;
String name;
String lastname;
String image;
String club;
String position;
String nationality;
String age;
int matches;
String goals;
String assists;
String saves;
PlayerDetails({this.id,this.name, this.lastname,this.image, this.club, this.position,
this.nationality, this.age, this.matches, this.goals, this.assists, this.saves});
#override
_PlayerDetailsState createState() => _PlayerDetailsState();
}
class _PlayerDetailsState extends State<PlayerDetails> {
List<Response> teams = [];
Future<void> getTeams(int id) async {
http.Response response = await http.get(
'https://v3.football.api-sports.io/transfers?player=$id',
headers: {'x-rapidapi-key': 'c52370f8295e1525b7f7ba38655e243f',
'x-rapidapi-host':'v3.football.api-sports.io'});
String body = response.body;
var data = jsonDecode(body);
List<dynamic> clubList = data['response'];
setState(() {
teams = clubList
.map((dynamic item) => Response.fromJson(item))
.toList();
});
}
#override
void initState() {
super.initState();
getTeams(widget.id);
}
#override
Widget build(BuildContext context) {
if(widget.matches == null ){
widget.matches == 0;
}
if(widget.goals == null ){
widget.goals == "0";
}
if(widget.assists == null ){
widget.assists == "0";
}
if(widget.saves == null ){
widget.saves == "0";
}
List<Stats> stats = [
Stats("Matches", widget.matches.toString() ),
Stats("Goals", widget.goals ),
Stats("Assists", widget.assists ),
Stats("Saves", widget.saves ),
];
return Scaffold(
appBar: AppBar(
title: Text("Player Details"),
backgroundColor: Colors.blue[300],
elevation: 0.0,
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [Colors.purple, Colors.blue])
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Colors.purple, Colors.black38])),
child: ListView(
children: [
SizedBox(
height: 20,
),
Container(
margin: EdgeInsets.fromLTRB(8.0,0,8.0,0),
width: double.infinity,
child: Card(
elevation: 4.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child:
Row(
children: <Widget>[
Container(
height: 60,
width: 60,
child:
Image.network(this.widget.image,
),
),
const SizedBox(width:10.0),
Spacer(),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget> [
Text(widget.name, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0,
)),
Text(widget.lastname, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0,
)),
const SizedBox(height: 5.0, ),
Text(widget.club, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0,
)),
const SizedBox(height: 5.0, ),
Text("Role : "+widget.position, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0, color: Colors.grey[600],
)),
const SizedBox(height: 5.0, ),
Text("Age : "+widget.age, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0, color: Colors.grey[600],
)),
const SizedBox(height: 5.0, ),
Text("Nationality : "+widget.nationality, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0, color: Colors.grey[600],
)),
],
),
],
),
),
),
),
Container(
margin: EdgeInsets.fromLTRB(10, 15, 0, 0),
child: Text(
"Season Stats",
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w900, color: Colors.white),
),
),
SizedBox(
height: 10,
),
Container(
padding: EdgeInsets.all(12.0),
child: GridView.builder(
shrinkWrap: true,
itemCount: stats.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0
),
itemBuilder: (BuildContext context, int index){
return Card(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
alignment: Alignment.topCenter,
padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
child: Text(stats[index].result,style: TextStyle(fontSize: 20.0)),
),
Container(
alignment: Alignment.bottomCenter,
child: Text(stats[index].title,style: TextStyle(fontSize: 25.0)),),
]
),
),
);
},
)
),
SizedBox(
height: 10,
),
Container(
margin: EdgeInsets.fromLTRB(10, 0, 0, 10),
child: Text(
"Teams",
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w900, color: Colors.white),
),
),
SizedBox(
height: 10,
),
Container(
margin: EdgeInsets.fromLTRB(5, 0, 5, 0),
child: ListView.builder(
shrinkWrap: true,
physics : NeverScrollableScrollPhysics(),
itemBuilder: (context, index){
return Card(
elevation: 4.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child:
Row(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(teams[index].transfers[index].teams.teamIn.logo),
),
const SizedBox(width:10.0),
Spacer(),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget> [
Text(teams[index].transfers[index].teams.teamIn.name, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0,
)),
const SizedBox(height: 5.0, ),
Text("joined : "+teams[index].transfers[index].date, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0, color: Colors.grey[600],
)),
],
),
],
),
),
);
},
itemCount: teams.length,
),
),
SizedBox(
height: 70,
),
],
),
)
),
);
}
}
class Stats{
String title;
String result;
Stats(this.title,this.result);
}
class Team {
String name;
String image;
String date;
Team(this.name,this.image,this.date);
}
i am trying to find a way to get all results , not just the first index of my api json
Example of nested ListviewBuilder , don't forget to add shrinkWrap inside the listview
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
shrinkWrap: true,
itemCount: teams.length,
itemBuilder: (BuildContext context, int index) {
List<Transfers> transfers = teams[index].transfers;
return ListView.builder(
shrinkWrap: true,
itemCount: transfers.length,
itemBuilder: (BuildContext context, int index) {
return Text(transfers[index].teams.teamIn.name);
},
) ;
},
),
);
}

iterating dynamic key in flutter

I am having a response as follows
{
"success": true,
"data": {
"store 1": [
{
"id": 27,
"cart_id": 5,
"item": {
"id": 35,
"name": "test prod 1"
}
},
{
"id": 28,
"cart_id": 56,
"item": {
"id": "jk",
"name": "test prod 2"
}
},
{
"id": 27,
"cart_id": 5,
"item": {
"id": 35,
"name": "test prod 1"
}
}
],
"store 2": [
{
"id": 27,
"cart_id": 5,
"item": {
"id": 35,
"name": "test prod 1"
}
},
{
"id": 28,
"cart_id": 56,
"item": {
"id": "jk",
"name": "test prod 2"
}
},
{
"id": 27,
"cart_id": 5,
"item": {
"id": 35,
"name": "test prod 1"
}
}
],
"store 3": [
{
"id": 27,
"cart_id": 5,
"item": {
"id": 35,
"name": "test prod 1"
}
},
{
"id": 28,
"cart_id": 56,
"item": {
"id": "jk",
"name": "test prod 2"
}
},
{
"id": 27,
"cart_id": 5,
"item": {
"id": 35,
"name": "test prod 1"
}
}
]
}
}
here is how i am itreating the value in api response
if (response.data['success'] == true) {
Map mapValue = jsonDecode(response.data);
List<ShoppingCartModel> cartList = [];
mapValue['data'].forEach((key, value) {
List<Store> store = [];
value.forEach((item) {
store.add(Store(
id: item['id'],
cartid: item['cart_id'],
product: item['product']));
});
cartList.add(ShoppingCartModel(sname: key, storeList: store));
});
print(cartList);
return cartList;
here is my model
class ShoppingCartModel {
String sname;
List<Store> storeList;
ShoppingCartModel({this.sname, this.storeList});
ShoppingCartModel.fromJson(Map<String, dynamic> json) {
sname = json['sname'];
storeList =
List<Store>.from(json["storeList"].map((x) => Store.fromJson(x)));
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sname'] = this.sname;
data['storeList'] = List<dynamic>.from(storeList.map((x) => x.toJson()));
return data;
}
}
class Store {
int id;
int cartid;
Item item;
Store({this.id, this.cartid, this.item});
Store.fromJson(Map<String, dynamic> json) {
id = json['id'];
cartid = json['cart_id'];
item = Item.fromJson(json["item"]);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['cart_id'] = this.cartid;
data['item'] = item.toJson();
return data;
}
}
class Item {
int id;
String name;
Item({
this.id,
this.name,
});
Item.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
//price = json['price'].toDouble();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
Here is part of my code in view
return ListView(
physics: AlwaysScrollableScrollPhysics(),
children: [
Container(
padding: EdgeInsets.all(16),
color: Colors.white,
child: Column(
children: List.generate(shoppingCartData.length,
(index) {
return _buildStoreName(index, boxImageSize);
}),
),
),
Container(
margin: EdgeInsets.only(top: 12),
padding: EdgeInsets.all(16),
color: Colors.white,
child: Column(
children: [
],
),
)
],
);
}
Column _buildStoreName(index, boxImageSize) {
//int quantity = shoppingCartData[index].qty;
return Column(
children: [
Container(
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
shoppingCartData[index].sname,
style: GlobalStyle.productName.copyWith(fontSize: 14),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
Expanded(
child: Column(
children: List.generate(
shoppingCartData[index].storeList.length, (indexStore) {
return _buildItem(shoppingCartData[index].storeList,
indexStore, boxImageSize);
}),
),
)
],
),
),
),
],
);
}
Column _buildItem(cartdata, indexStore, boxImageSize) {
int quantity = cartdata[indexStore].item.quantity;
return Column(
children: [
Container(
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
GestureDetector(
onTap: () {
),
SizedBox(
width: 10,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () {
},
child: Text(
cartdata[indexStore].item.name,
style: GlobalStyle.productName.copyWith(fontSize: 14),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
],
),
)
],
),
),
),
)
],
);
}
here is my required view
i am getting error while mapping itself.Just the store name are different but the keys inside are same
I need to iterate first list as store and second list as iem values in a list view
You can not access the response.data as map before you decode it.
Try jsonDecode() before this condition
if (response.data['success'] == true)
Example:
var res = jsonDecode(response.data);
if(res['success'] == true){
// do rest of your operation
}
I'm using Get package for this code:
products_data.dart
const String productData = '''
{
"success": true,
"data": {
...
}
}
''';
item_model.dart
import 'package:flutter/foundation.dart';
class ItemModel {
dynamic id;
String name;
ItemModel({#required this.id, #required this.name});
ItemModel.fromJson(Map<String, dynamic> data) {
id = data['id'];
name = data['name'];
}
}
asset_model.dart
import 'package:flutter/material.dart';
import 'package:getx_json/models/item_model.dart';
class AssetModel {
int id;
int cartId;
ItemModel item;
AssetModel({#required this.id, #required this.cartId, #required this.item});
AssetModel.fromJson(Map<String, dynamic> data) {
id = data['id'];
cartId = data['cart_id'];
item = ItemModel.fromJson(data['item']);
}
Card showCard() => Card(
color: Colors.lightBlue,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('id: $id'),
Text('cart_id: $cartId'),
Text('Item', style: TextStyle(fontWeight: FontWeight.bold)),
Container(
width: double.infinity,
child: Padding(
padding: const EdgeInsets.only(left: 10, right: 10),
child: Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('id: ${item.id}'),
Text('name: ${item.name}'),
],
),
),
),
),
],
),
);
}
shopping_controller.dart
import 'dart:convert';
import 'package:get/get.dart';
import 'package:getx_json/models/asset_model.dart';
import 'package:getx_json/src/shared/products_data.dart';
class ShoppingController extends GetxController {
var assets = Map<String, List<AssetModel>>().obs;
#override
void onInit(){
super.onInit();
fetchProducts();
}
void fetchProducts() async {
await Future.delayed(Duration(seconds: 1));
Map<String, dynamic> response = jsonDecode(productData);
if (response['success'] == true) {
var data = Map<String, List<AssetModel>>();
(response['data'] as Map<String, dynamic>).forEach((key, value) {
data[key] = (value as List).map((e) => AssetModel.fromJson(e)).toList();
});
assets.addAll(data);
}
}
}
home_page.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_json/src/controllers/shopping_controller.dart';
class HomePage extends StatelessWidget {
/* ---------------------------------------------------------------------------- */
const HomePage({Key key}) : super(key: key);
/* ---------------------------------------------------------------------------- */
#override
Widget build(BuildContext context) {
final stores = Get.put(ShoppingController());
return Scaffold(
body: SafeArea(
child:
Obx(() => stores.assets.length > 0 ? buildListView() : buildText()),
),
);
}
Widget buildListView() {
final stores = Get.find<ShoppingController>().assets;
final titles = stores.keys.toList();
return ListView.builder(
physics: ScrollPhysics(),
scrollDirection: Axis.vertical,
itemCount: stores.length,
itemBuilder: (context, index) => Card(
color: Colors.orange,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(titles[index], style: TextStyle(fontWeight: FontWeight.bold)),
ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: stores[titles[index]].length,
itemBuilder: (context, idx) => stores[titles[index]][idx].showCard(),
),
],
),
),
),
);
}
Widget buildText() {
final stores = Get.find<ShoppingController>();
return Text(stores.assets.toString());
}
}

Unable to access the data from the provider

I wish to print the quantity of the items selected but am not able to do so. I am using providers to access data but it's showing some error. The same method worked when I applied it elsewhere but it doesn't seem to work here Please help.
Snippet for the type of data I receive:
{
"delivery_status": true,
"coupon_code": null,
"cart": [
{
"food_item_id": "2c7289c1-17fb-4f3a-90af-7a014e051c53",
"name": "Grape",
"price": 35.0,
"category": "Fresh Fruit Juice",
"available": true,
"veg": false,
"egg": false,
"restaurant": "9adafbd7-a9ba-4890-b707-c9d619c72f02",
"quantity": 1
},
{
"food_item_id": "be303557-90ce-4f9c-a30f-5a6d650977b6",
"name": "Mix Juice",
"price": 35.0,
"category": "Fresh Fruit Juice",
"available": true,
"veg": false,
"egg": false,
"restaurant": "9adafbd7-a9ba-4890-b707-c9d619c72f02",
"quantity": 2
},
{
"food_item_id": "13fb9de8-c774-4f6d-af66-74cc6dedbf14",
"name": "Boondi Raita",
"price": 110.0,
"category": "Salad Bar",
"available": true,
"veg": false,
"egg": false,
"restaurant": "9adafbd7-a9ba-4890-b707-c9d619c72f02",
"quantity": 1
}
],
"total_amount": 215.0
}
Snippet for Mapping Logic:
CartItem _items = CartItem(
couponCode: '',
deliveryStatus: false,
totalAmount: 0.0,
);
CartItem get items {
return _items;
}
// ===============================Looks Here
List<MenuItem> _cartProducts = [];
List<MenuItem> get cartProducts {
return [..._cartProducts];
}
Future<void> getCart() async {
Map<String, String> header = {
'Content-type': 'application/json',
'Authorization': accessToken,
};
try {
final response = await http.get(apiURL + getCartURL, headers: header);
print(response.statusCode);
if (response.statusCode == 200) {
final res = jsonDecode(response.body) as Map<String, dynamic>;
if (res == null) {
return _items;
}
_items = CartItem(
deliveryStatus: res['delivery_status'],
couponCode: res['coupon_code'],
totalAmount: res['total_amount'],
);
// ===============================Looks Here
List<MenuItem> cartStuff = [];
res["cart"].forEach((cartData) {
cartStuff.add(
MenuItem(
foodItemId: cartData['food_item_id'],
category: cartData['category'],
name: cartData['name'],
isAvailable: cartData['available'],
isEgg: cartData['egg'],
isVeg: cartData['veg'],
price: cartData['price'],
restaurant: cartData['restaurant'],
quantity: cartData['quantity'],
),
);
});
// ===============================Looks Here
_cartProducts = cartStuff;
print(_cartProducts);
notifyListeners();
} else if (response.statusCode == 403) {
fetchNewAToken().then((_) {
if (accessToken != null && refreshToken != null) getCart();
notifyListeners();
});
}
} catch (e) {
print("Error in getting the Cart");
print(e);
}
}
Snippet for displaying the data:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../globals/text_styles.dart';
import '../../globals/colors.dart';
import '../../providers/cart.dart';
class QuantityButton extends StatefulWidget {
//The item id received is correct so the error occurs is in accessing the data from the provider.
final itemID;
QuantityButton(this.itemID);
#override
_QuantityButtonState createState() => _QuantityButtonState();
}
class _QuantityButtonState extends State<QuantityButton> {
#override
Widget build(BuildContext context) {
final cartData = Provider.of<Cart>(context);
final cartQty =
cartData.cartProducts.where((item) => item.foodItemId == widget.itemID);
return Container(
width: 100,
height: 40,
child: Card(
color: primaryColor.withOpacity(0.9),
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.black),
borderRadius: BorderRadius.circular(10),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
onTap: () {
cartData.deleteItems(widget.itemID);
},
child: Icon(
Icons.arrow_left,
color: Colors.white,
size: 25,
),
),
Spacer(),
Container(
child: Padding(
padding: const EdgeInsets.all(3.0),
child: Text(
// =========== Print Quantity Here ===========
'',
style: valueTextStyle,
),
),
),
Spacer(),
GestureDetector(
onTap: () {
cartData.addItems(widget.itemID);
},
child: Icon(
Icons.arrow_right,
color: Colors.white,
size: 25,
),
),
],
),
),
);
}
}