Related
i tried to decode my json and take the values to futurebuilder in flutter when decode my json appear formatexception:unexpectedcharacter,tried to storage in a String and in List, think my error think is how to toke data,how to storage my json decode,
Thanks
my code
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:oauth2_client/spotify_oauth2_client.dart';
import 'package:ui/Models/segundapantalla.dart';
import 'newmodel.dart';
class callttoappi {
Future getatatodapi() async {
String url =
'https://api.spotify.com/v1/playlists/37i9dQZF1DXcBWIGoYBM5M/tracks';
var client = SpotifyOAuth2Client(
redirectUri: 'com.example.ui://callback',
customUriScheme: 'com.example.ui');
var tknResp = await client.getTokenWithAuthCodeFlow(
clientId: 'client id',
scopes: [
'user-read-email',
'user-read-private',
]);
if (tknResp != null) {
var headers = {
'Authorization': 'Bearer ${tknResp.accessToken}',
};
var request = await http.Request(
'GET', Uri.parse('https://api.spotify.com/v1/browse/new-releases'));
request.headers.addAll(headers);
http.StreamedResponse response =
await request.send().timeout(const Duration(seconds: 20));
if (response.statusCode == 200) {
//String reponsedata = await response.stream.bytesToString();
//print(await response.stream.bytesToString());
Map<String, dynamic> userMap = jsonDecode(await response.stream.bytesToString());
var user = Item.fromJson(userMap);
print(userMap);
//Map<String,dynamic> json = jsonDecode(await response.stream.bytesToString());
//print(json);
return Item.fromJson(jsonDecode(json.toString()));
} else {
print(response.reasonPhrase);
}
}
}
}
my model class,quicktype website or another page this like github projects to obtain my json
class Newmodel {
Newmodel({
required this.albums,
});
final Albums? albums;
factory Newmodel.fromJson(Map<String, dynamic> json){
return Newmodel(
albums: json["albums"] == null ? null : Albums.fromJson(json["albums"]),
);
}
Map<String, dynamic> toJson() => {
"albums": albums?.toJson(),
};
#override
String toString(){
return '$albums';
}
}
class Albums {
Albums({
required this.href,
required this.items,
required this.limit,
required this.next,
required this.offset,
required this.previous,
required this.total,
});
final String? href;
final List<Item> items;
final int? limit;
final String? next;
final int? offset;
final dynamic previous;
final int? total;
factory Albums.fromJson(Map<String, dynamic> json){
return Albums(
href: json["href"],
items: json["items"] == null ? [] : List<Item>.from(json["items"]!.map((x) => Item.fromJson(x))),
limit: json["limit"],
next: json["next"],
offset: json["offset"],
previous: json["previous"],
total: json["total"],
);
}
Map<String, dynamic> toJson() => {
"href": href,
"items": List<Item>.from(items.map((x) => x.toJson())),
"limit": limit,
"next": next,
"offset": offset,
"previous": previous,
"total": total,
};
#override
String toString(){
return '$href, $items, $limit, $next, $offset, $previous, $total';
}
}
class Item {
Item({
required this.albumType,
required this.artists,
required this.availableMarkets,
required this.externalUrls,
required this.href,
required this.id,
required this.images,
required this.name,
required this.releaseDate,
required this.releaseDatePrecision,
required this.totalTracks,
required this.type,
required this.uri,
});
final String? albumType;
final List<Artist> artists;
final List<String> availableMarkets;
final ExternalUrls? externalUrls;
final String? href;
final String? id;
final List<Image> images;
final String? name;
final DateTime? releaseDate;
final String? releaseDatePrecision;
final int? totalTracks;
final String? type;
final String? uri;
factory Item.fromJson(Map<String, dynamic> json){
return Item(
albumType: json["album_type"],
artists: json["artists"] == null ? [] : List<Artist>.from(json["artists"]!.map((x) => Artist.fromJson(x))),
availableMarkets: json["available_markets"] == null ? [] : List<String>.from(json["available_markets"]!.map((x) => x)),
externalUrls: json["external_urls"] == null ? null : ExternalUrls.fromJson(json["external_urls"]),
href: json["href"],
id: json["id"],
images: json["images"] == null ? [] : List<Image>.from(json["images"]!.map((x) => Image.fromJson(x))),
name: json["name"],
releaseDate: json["release_date"] == null ? null : DateTime.parse(json["release_date"]),
releaseDatePrecision: json["release_date_precision"],
totalTracks: json["total_tracks"],
type: json["type"],
uri: json["uri"],
);
}
Map<String, dynamic> toJson() => {
"album_type": albumType,
"artists": List<Artist>.from(artists.map((x) => x.toJson())),
"available_markets": List<String>.from(availableMarkets.map((x) => x)),
"external_urls": externalUrls?.toJson(),
"href": href,
"id": id,
"images": List<Image>.from(images.map((x) => x.toJson())),
"name": name,
//"release_date": "${releaseDate.year.toString().padLeft(4'0')}-${releaseDate.month.toString().padLeft(2'0')}-${releaseDate.day.toString().padLeft(2'0')}",
"release_date_precision": releaseDatePrecision,
"total_tracks": totalTracks,
"type": type,
"uri": uri,
};
#override
String toString(){
return '$albumType, $artists, $availableMarkets, $externalUrls, $href, $id, $images, $name, $releaseDate, $releaseDatePrecision, $totalTracks, $type, $uri';
}
}
viewpage class
class lodeo extends StatefulWidget {
#override
State<lodeo> createState() => _WeatherPageState();
}
class _WeatherPageState extends State<lodeo> {
Future getData() async {
return await callttoappi().getatatodapi();
}
Future<dynamic>? _myData;
#override
void initState() {
setState(() {
_myData = getData();
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If error occured
if (snapshot.hasError) {
return Center(
child: Text(
'${snapshot.error.toString()} occurred',
style: TextStyle(fontSize: 18),
),
);
// if data has no errors
} else if (snapshot.hasData) {
// Extracting data from snapshot object
final data = snapshot.data as Item;
return Container(
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment(0.8, 1),
colors: <Color>[
Color.fromARGB(255, 65, 89, 224),
Color.fromARGB(255, 83, 92, 215),
Color.fromARGB(255, 86, 88, 177),
Color(0xfff39060),
Color(0xffffb56b),
],
tileMode: TileMode.mirror,
),
),
width: double.infinity,
height: double.infinity,
child: SafeArea(
child: Column(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data.albumType.toString(),
style: TextStyle(
fontSize: 30,
color: Colors.white,
fontWeight: FontWeight.bold),
),
Text(
data.id.toString(),
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold),
),
Text(
data.name.toString(),
style: TextStyle(
fontSize: 50,
color: Colors.white,
fontWeight: FontWeight.bold),
),
],
),
),
],
),
),
);
}
} else if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return Center(
child: Text("${snapshot.connectionState} occured"),
);
}
return Center(
child: Text("Server timed out!"),
);
},
future: _myData!,
),
);
}
enter code here
I'm trying to display a list from api with GET request. But it keeps showing this error:
NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("depId")
The thing is I don't use depId at all for this request and it's not even in the object that I'm using to make this request so I don't know from where it gets null value because when I use it in my previous request it works totally fine.
Here is the API request
static Future<List<Athlete>> getAthletesByTeamKey(
int depId, int teamId) async {
try {
final response = await http.get(
Uri.parse(
'$uri/get-athletes-by-team-key?depId=$depId&teamId=$teamId&page=0&length=50'),
headers: {
'Authorization': 'Basic ...',
'Content-Type': 'application/json',
'Accept': 'application/json'
});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
if (response.statusCode == 200) {
if (response.body.isNotEmpty) {
print('response.body.isNotEmpty');
List jsonResponse = json.decode(utf8.decode(response.bodyBytes));
return jsonResponse
.map((athlete) => Athlete.fromJson(athlete))
.toList();
} else if (response.body.isEmpty) {
print('response.body.isEmpty');
throw Exception();
}
}
} catch (e) {
print('catch');
logger.e(e.toString());
}
return getAthletesByTeamKey(depId, teamId, context);
}
It prints the print('response.body.isNotEmpty');and then it goes into catch
My Athlete object
List<Athlete> athleteFromJson(String str) =>
List<Athlete>.from(json.decode(str).map((x) => Athlete.fromJson(x)));
String athleteToJson(List<Athlete> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Athlete {
late int id;
late String firstName;
late String lastName;
late String fatherName;
late int currentMonthPresences;
late bool isSelected = false;
late bool hasDebt;
Department? department;
Team? team;
Athlete(
{required this.id,
required this.firstName,
required this.lastName,
required this.fatherName,
required this.currentMonthPresences,
this.isSelected = false,
required this.hasDebt,
this.department,
this.team});
Athlete.newSelectedAthlete(this.id, this.department, this.team); //I use it for another screen
factory Athlete.fromJson(Map<String, dynamic> json) => Athlete(
id: json['id'],
firstName: json['firstName'],
lastName: json['lastName'],
fatherName: json['fatherName'],
currentMonthPresences: json['currentMonthPresences'],
hasDebt: json['hasDebt'],
department: Department.fromJson(json['department']),
team: Team.fromJson(json['team']),
);
Map<String, dynamic> toJson() => {
'id': id,
'firstName': firstName,
'lastName': lastName,
'fatherName': fatherName,
'currentMonthPresences': currentMonthPresences,
'isSelected': isSelected,
'hasDebt': hasDebt,
'department': department,
'team': team,
};
}
Department object
class Department {
int id;
String depName;
Department({required this.id, required this.depName});
factory Department.fromJson(Map<String, dynamic> json) => Department(
id: json['id'],
depName: json['depName'],
);
Map<String, dynamic> toJson() => {
"id": id,
"depName": depName,
};
}
Team object
class Team {
final TeamKey teamKey;
final String teamName;
final int hidden;
final User user;
final String depName;
Team(
{required this.teamKey,
required this.teamName,
required this.hidden,
required this.user,
required this.depName});
factory Team.fromJson(Map<String, dynamic> json) => Team(
teamKey: TeamKey.fromJson(json['teamKey']),
teamName: json['teamName'],
hidden: json['hidden'],
user: User.fromJson(json['user']),
depName: json['depName'],
);
Map<String, dynamic> toJson() => {
'teamKey': teamKey,
'teamName': teamName,
'hidden': hidden,
'user': user,
'depName': depName,
};
}
and the TeamKey object that has the variable depId but I don't use it at all
class TeamKey {
int depId;
int teamId;
TeamKey({required this.depId, required this.teamId});
factory TeamKey.fromJson(Map<String, dynamic> json) => TeamKey(
depId: json['depId'],
teamId: json['teamId'],
);
Map<String, dynamic> toJson() => {
"depId": depId,
"teamId": teamId,
};
}
The screen I'm trying to display my list
class AthleteScreen extends StatefulWidget {
const AthleteScreen(this._team, {Key? key}) : super(key: key);
final Team _team;
#override
State<AthleteScreen> createState() => _AthleteScreenState();
}
class _AthleteScreenState extends State<AthleteScreen> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final myController = TextEditingController();
final controller = TextEditingController();
Future<List<Athlete>>? futureAthletebyTeamKey;
Future<List<Presence>>? futureGetPresences;
final List<Athlete> _athlete = [];
#override
void initState() {
futureAthletebyTeamKey = ApiService.getAthletesByTeamKey();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
body: Stack(
children: [
SingleChildScrollView(
child: Column(children: [
const SizedBox(
height: 10,
),
FutureBuilder<List<Athlete>>(
future: futureAthletebyTeamKey,
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
List<Athlete> _athlete = snapshot.data;
return ListView.builder(
shrinkWrap: true,
cacheExtent: 34,
primary: true,
physics: const ClampingScrollPhysics(),
padding: const EdgeInsets.only(
top: 10,
bottom: 56,
),
itemCount: _athlete.length,
itemBuilder: (BuildContext context, int i) {
return CheckboxListTile(
title: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'ID: ${_athlete[i].id}',
style: const TextStyle(
color: Colors.blue, fontSize: 14),
),
const SizedBox(
width: 5,
),
],
),
Row(
children: [
Flexible(
child: Text(
'${_athlete[i].lastName} ${_athlete[i].firstName}',
style: const TextStyle(
color: Colors.black,
fontFamily: 'Cera',
fontWeight: FontWeight.bold,
fontSize: 18),
),
),
],
),
const SizedBox(
height: 5,
),
});
} else if (snapshot.hasError) {
logger.e('${snapshot.error}');
}
return const Center(
heightFactor: 20,
child: CircularProgressIndicator.adaptive(),
);
},
),
]),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
width: double.infinity,
height: 60,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
disabledBackgroundColor: Colors.grey),
onPressed: () async {
Navigator.of(context).pushNamed(
SelectedAthletes.routeName,
arguments: selectedAthlete.toList());
}),
child: Column(
children: [
const Text(
'ΝΕΧΤ',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 18),
),
],
),
),
),
),
],
),
);
}
}
I'll be very thankful if someone took time to help me! Thanks in advance!
You actually use depId.
So let's follow along with your JSON.
When you decode the athlete you do:
factory Athlete.fromJson(Map<String, dynamic> json) => Athlete(
...
department: Department.fromJson(json['department']),
team: Team.fromJson(json['team']),
);
So the Athlete.fromJson() is calling Team.fromJson(). Let's look at it
factory Team.fromJson(Map<String, dynamic> json) => Team(
teamKey: TeamKey.fromJson(json['teamKey']),
...
);
Team.fromJson() iscalling TeamKey.fromJson(). Let's look at that.
factory TeamKey.fromJson(Map<String, dynamic> json) => TeamKey(
depId: json['depId'],
teamId: json['teamId'],
);
TeamKey.fromJson() wants the 'depId'.
Your JSON should look like:
team: {
teamKey: {
depId: ...
}
}
Double check your JSON to make sure your structure is good. Your code will actually decode along with Athlete his Team and TeamKey where you access 'depId'.
You should either remove the teamKey, or resolve it by following along the path of the original JSON you are trying to parse and see if your structure is in align with it.
I use this json to list stocks(BIST). https://bigpara.hurriyet.com.tr/api/v1/hisse/list This is my model:
// To parse this JSON data, do
//
// final bigParaList = bigParaListFromJson(jsonString);
import 'dart:convert';
BigParaList bigParaListFromJson(String str) => BigParaList.fromJson(json.decode(str));
String bigParaListToJson(BigParaList data) => json.encode(data.toJson());
class BigParaList {
BigParaList({
required this.code,
required this.data,
});
String code;
List<Datum> data;
factory BigParaList.fromJson(Map<String, dynamic> json) => BigParaList(
code: json["code"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"code": code,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
required this.id,
required this.kod,
required this.ad,
required this.tip,
});
int? id;
String? kod;
String? ad;
Tip? tip;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
kod: json["kod"],
ad: json["ad"],
tip: tipValues.map[json["tip"]],
);
Map<String, dynamic> toJson() => {
"id": id,
"kod": kod,
"ad": ad,
"tip": tipValues.reverse[tip],
};
}
enum Tip { HISSE }
final tipValues = EnumValues({
"Hisse": Tip.HISSE
});
class EnumValues<T> {
Map<String, T> map;
Map<T, String>? reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
return reverseMap ??= map.map((k, v) => MapEntry(v, k));
}
}
And this is my 2nd model which includes stock details. https://bigpara.hurriyet.com.tr/api/v1/borsa/hisseyuzeysel/AEFES (AEFES is a sample any of the stocks can be used from the previous list)
// To parse this JSON data, do
//
// final bigParaDetay = bigParaDetayFromJson(jsonString);
import 'dart:convert';
BigParaDetay bigParaDetayFromJson(String str) => BigParaDetay.fromJson(json.decode(str));
String bigParaDetayToJson(BigParaDetay data) => json.encode(data.toJson());
class BigParaDetay {
BigParaDetay({
required this.code,
required this.data,
});
String code;
Map<String, Datum?> data;
factory BigParaDetay.fromJson(Map<String, dynamic> json) => BigParaDetay(
code: json["code"],
data: Map.from(json["data"]).map((k, v) => MapEntry<String, Datum?>(k, v == null ? null : Datum.fromJson(v))),
);
Map<String, dynamic> toJson() => {
"code": code,
"data": Map.from(data).map((k, v) => MapEntry<String, dynamic>(k, v == null ? null : v.toJson())),
};
}
class Datum {
Datum({
this.sembolid,
this.sembol,
this.tarih,
this.sektorid,
this.alis,
this.satis,
this.acilis,
this.yuksek,
this.yukseK1,
this.yukseK2,
this.dusuk,
this.dusuK1,
this.dusuK2,
this.kapanis,
this.kapaniS1,
this.kapaniS2,
this.hacimlot,
this.hacimloT1,
this.hacimloT2,
this.aort,
this.aorT1,
this.aorT2,
this.hacimtldun,
this.hacimyuzdedegisim,
this.hacimtl,
this.hacimtL1,
this.hacimtL2,
this.dunkukapanis,
this.oncekikapanis,
this.izafikapanis,
this.tavan,
this.taban,
this.yilyuksek,
this.yildusuk,
this.ayyuksek,
this.aydusuk,
this.haftayuksek,
this.haftadusuk,
this.oncekiyilkapanis,
this.oncekiaykapanis,
this.oncekihaftakapanis,
this.yilortalama,
this.ayortalama,
this.haftaortalama,
this.yuzdedegisimS1,
this.yuzdedegisimS2,
this.yuzdedegisim,
this.fiyatadimi,
this.kaykar,
this.sermaye,
this.saklamaor,
this.netkar,
this.net,
this.fiyatkaz,
this.piydeg,
this.kapanisfark,
this.donem,
this.ozsermaye,
this.beta,
this.xU100Ag,
this.aciklama,
});
int? sembolid;
String? sembol;
DateTime? tarih;
int? sektorid;
double? alis;
double? satis;
double? acilis;
double? yuksek;
double? yukseK1;
double? yukseK2;
double? dusuk;
double? dusuK1;
double? dusuK2;
double? kapanis;
double? kapaniS1;
double? kapaniS2;
int? hacimlot;
int? hacimloT1;
int? hacimloT2;
double? aort;
double? aorT1;
double? aorT2;
int? hacimtldun;
double? hacimyuzdedegisim;
int? hacimtl;
int? hacimtL1;
int? hacimtL2;
int? dunkukapanis;
int? oncekikapanis;
int? izafikapanis;
double? tavan;
double? taban;
double? yilyuksek;
double? yildusuk;
double? ayyuksek;
double? aydusuk;
double? haftayuksek;
double? haftadusuk;
double? oncekiyilkapanis;
double? oncekiaykapanis;
double? oncekihaftakapanis;
double? yilortalama;
double? ayortalama;
double? haftaortalama;
double? yuzdedegisimS1;
double? yuzdedegisimS2;
double? yuzdedegisim;
double? fiyatadimi;
int? kaykar;
int? sermaye;
double? saklamaor;
int? netkar;
double? net;
double? fiyatkaz;
double? piydeg;
dynamic kapanisfark;
String? donem;
int? ozsermaye;
double? beta;
double? xU100Ag;
String? aciklama;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
sembolid: json["sembolid"],
sembol: json["sembol"],
tarih: DateTime.parse(json["tarih"]),
sektorid: json["sektorid"],
alis: json["alis"].toDouble(),
satis: json["satis"].toDouble(),
acilis: json["acilis"].toDouble(),
yuksek: json["yuksek"].toDouble(),
yukseK1: json["yukseK1"].toDouble(),
yukseK2: json["yukseK2"].toDouble(),
dusuk: json["dusuk"].toDouble(),
dusuK1: json["dusuK1"].toDouble(),
dusuK2: json["dusuK2"].toDouble(),
kapanis: json["kapanis"].toDouble(),
kapaniS1: json["kapaniS1"].toDouble(),
kapaniS2: json["kapaniS2"].toDouble(),
hacimlot: json["hacimlot"],
hacimloT1: json["hacimloT1"],
hacimloT2: json["hacimloT2"],
aort: json["aort"].toDouble(),
aorT1: json["aorT1"].toDouble(),
aorT2: json["aorT2"].toDouble(),
hacimtldun: json["hacimtldun"],
hacimyuzdedegisim: json["hacimyuzdedegisim"].toDouble(),
hacimtl: json["hacimtl"],
hacimtL1: json["hacimtL1"],
hacimtL2: json["hacimtL2"],
dunkukapanis: json["dunkukapanis"],
oncekikapanis: json["oncekikapanis"],
izafikapanis: json["izafikapanis"],
tavan: json["tavan"].toDouble(),
taban: json["taban"].toDouble(),
yilyuksek: json["yilyuksek"].toDouble(),
yildusuk: json["yildusuk"].toDouble(),
ayyuksek: json["ayyuksek"].toDouble(),
aydusuk: json["aydusuk"].toDouble(),
haftayuksek: json["haftayuksek"].toDouble(),
haftadusuk: json["haftadusuk"].toDouble(),
oncekiyilkapanis: json["oncekiyilkapanis"].toDouble(),
oncekiaykapanis: json["oncekiaykapanis"].toDouble(),
oncekihaftakapanis: json["oncekihaftakapanis"].toDouble(),
yilortalama: json["yilortalama"].toDouble(),
ayortalama: json["ayortalama"].toDouble(),
haftaortalama: json["haftaortalama"].toDouble(),
yuzdedegisimS1: json["yuzdedegisimS1"].toDouble(),
yuzdedegisimS2: json["yuzdedegisimS2"].toDouble(),
yuzdedegisim: json["yuzdedegisim"].toDouble(),
fiyatadimi: json["fiyatadimi"].toDouble(),
kaykar: json["kaykar"],
sermaye: json["sermaye"],
saklamaor: json["saklamaor"].toDouble(),
netkar: json["netkar"],
net: json["net"].toDouble(),
fiyatkaz: json["fiyatkaz"].toDouble(),
piydeg: json["piydeg"].toDouble(),
kapanisfark: json["kapanisfark"],
donem: json["donem"],
ozsermaye: json["ozsermaye"],
beta: json["beta"].toDouble(),
xU100Ag: json["xU100AG"].toDouble(),
aciklama: json["aciklama"],
);
Map<String, dynamic> toJson() => {
"sembolid": sembolid,
"sembol": sembol,
"tarih": tarih.toString(),
"sektorid": sektorid,
"alis": alis,
"satis": satis,
"acilis": acilis,
"yuksek": yuksek,
"yukseK1": yukseK1,
"yukseK2": yukseK2,
"dusuk": dusuk,
"dusuK1": dusuK1,
"dusuK2": dusuK2,
"kapanis": kapanis,
"kapaniS1": kapaniS1,
"kapaniS2": kapaniS2,
"hacimlot": hacimlot,
"hacimloT1": hacimloT1,
"hacimloT2": hacimloT2,
"aort": aort,
"aorT1": aorT1,
"aorT2": aorT2,
"hacimtldun": hacimtldun,
"hacimyuzdedegisim": hacimyuzdedegisim,
"hacimtl": hacimtl,
"hacimtL1": hacimtL1,
"hacimtL2": hacimtL2,
"dunkukapanis": dunkukapanis,
"oncekikapanis": oncekikapanis,
"izafikapanis": izafikapanis,
"tavan": tavan,
"taban": taban,
"yilyuksek": yilyuksek,
"yildusuk": yildusuk,
"ayyuksek": ayyuksek,
"aydusuk": aydusuk,
"haftayuksek": haftayuksek,
"haftadusuk": haftadusuk,
"oncekiyilkapanis": oncekiyilkapanis,
"oncekiaykapanis": oncekiaykapanis,
"oncekihaftakapanis": oncekihaftakapanis,
"yilortalama": yilortalama,
"ayortalama": ayortalama,
"haftaortalama": haftaortalama,
"yuzdedegisimS1": yuzdedegisimS1,
"yuzdedegisimS2": yuzdedegisimS2,
"yuzdedegisim": yuzdedegisim,
"fiyatadimi": fiyatadimi,
"kaykar": kaykar,
"sermaye": sermaye,
"saklamaor": saklamaor,
"netkar": netkar,
"net": net,
"fiyatkaz": fiyatkaz,
"piydeg": piydeg,
"kapanisfark": kapanisfark,
"donem": donem,
"ozsermaye": ozsermaye,
"beta": beta,
"xU100AG": xU100Ag,
"aciklama": aciklama,
};
}
This is where i call api :
class Hisseler extends StatefulWidget {
const Hisseler({Key? key}) : super(key: key);
#override
State<Hisseler> createState() => _HisselerState();
}
class _HisselerState extends State<Hisseler> {
Future<BigParaDetay?> callHisseDetail(String kod) async {
try {
final detailUrl = Uri.parse("https://bigpara.hurriyet.com.tr/api/v1/borsa/hisseyuzeysel/$kod");
final response = await http.get(detailUrl);
if(response.statusCode == 200){
final data = bigParaDetayFromJson(response.body);
return data;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
return null;
}
final scaffoldKey = GlobalKey<ScaffoldState>();
final url = Uri.parse('https://bigpara.hurriyet.com.tr/api/v1/hisse/list');
var counter;
BigParaList? hisseResult;
Future callHisse() async {
try{
final response = await http.get(url,);
if(response.statusCode == 200){
var data = bigParaListFromJson(response.body);
if(mounted);
setState(() {
counter = data.data.length;
hisseResult = data;
});
return data;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
callHisse();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: false,
automaticallyImplyLeading: false,
title: Text(
'Hisseler'
),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: counter != null ?
ListView.separated(
itemCount: counter,
separatorBuilder: (context, index) => SizedBox(
height: 2,
),
itemBuilder: (context, index){
return Card(
child: ListTile(
title: Text(hisseResult?.data[index].kod.toString()??""),
subtitle: Text(hisseResult?.data[index].ad??""),
onTap: () async {
final detailData = await callHisseDetail(hisseResult?.data[index].kod ?? "");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StocksDetailScreen(
subtitle: hisseResult?.data[index].ad??"",
title: hisseResult?.data[index].kod??"",
data: detailData,
),
),
);
}
),
);
}) : Center(child: CircularProgressIndicator(
)),
),
),
);
}
}
Everything is ok until here. This is the detail page structure when I want to show stock details from the 2nd model to the stock I call from the first API.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../blocs/ads_bloc.dart';
import '../models/apis/bigpara_detay.dart';
import '../widgets/banner_ad_admob.dart';
class StocksDetailScreen extends StatelessWidget {
final String title;
final String subtitle;
final BigParaDetay? data;
const StocksDetailScreen({
Key? key,
required this.title,
required this.subtitle,
this.data,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title,style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900),),
),
body: SafeArea(
bottom: true,
top: false,
maintainBottomViewPadding: true,
child: Column(
children: [
Expanded(
child: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(data.sembol,style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900),),
],
),
),
),
Divider(height: 3.6,),
SizedBox(height: 50,),
Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Text(subtitle,style: TextStyle(fontSize: 20,fontWeight: FontWeight.w600), textAlign: TextAlign.center,),
),
)
],
),
),
],
),
),
// -- Banner ads --
context.watch<AdsBloc>().bannerAdEnabled == false ? Container()
: BannerAdAdmob() //admob
//: BannerAdFb() //fb
],
),
)
);
}
}
As you see here I will use details from the 2nd model. This page is not finished. But I want to call data from 2nd model to continue.
I tried
Text(data.sembol,style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900),),
to show the data from the 2nd model but I get this error: The property 'symbol' can't be unconditionally accessed because the receiver can be 'null'.
How can I fix this? How can I call data from the 2n model on the detail page? Thanks for your help
BigParaDetay
Future<BigParaDetay?> callHisseDetail(String kod) async {
try {
final detailUrl = Uri.parse("https://bigpara.hurriyet.com.tr/api/v1/borsa/hisseyuzeysel/$kod");
final response = await http.get(detailUrl);
if(response.statusCode == 200){
final data = bigParaDetayFromJson(response.body);
return data;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
return null;
}
Your data is nullable final BigParaDetay? data;, provide default value on cases like
Text(data?.data??"got null", ),
if you like access sembol it will be like
Text("${data?.data.values.first["sembol"]}")
//or
Text("${data?.data.values?.first["sembol"]}")
data?.data will provide a map of
I want to fetch images from API. I've created a model class but the problem is I have accessed the img_path from the model class but am not able to access the image from the model class because I want to concatenate img_path+image to display on the home page. Below I've mentioned the model class and home page code. please find and check the below classes.
Home Page :-
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'NavDrawer.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'banner_model.dart';
var paddingBottom = 48.0;
var androidDeviceInfo;
var identifier;
var token = "debendra";
var token1;
class HomePage extends StatelessWidget {
final String apiUrl1 = "https://newbharatbiz.in/mobile_api/v4/all_banner.php";
Future<BannerModel> fetchAlbum() async {
final response = await http.get(Uri.parse(apiUrl1));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return BannerModel.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: NavDrawer(),
appBar:
AppBar(title: Text('New Bharat Biz'), centerTitle: true, actions: [
IconButton(
onPressed: () async {},
icon: Icon(Icons.search),
),
]),
body: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
FutureBuilder<BannerModel>(
future: fetchAlbum(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final List<String> imagesList = [
snapshot.data!.imgPath + "1542696267.png"
];
return Container(
child: CarouselSlider(
options: CarouselOptions(
height: 330,
aspectRatio: 16 / 9,
viewportFraction: 0.8,
initialPage: 0,
enableInfiniteScroll: true,
reverse: false,
autoPlay: true,
autoPlayInterval: Duration(seconds: 3),
autoPlayAnimationDuration: Duration(milliseconds: 800),
autoPlayCurve: Curves.fastOutSlowIn,
enlargeCenterPage: true,
),
items: imagesList
.map(
(item) => Container(
child: Center(
child: Image.network(item,
fit: BoxFit.cover, width: 1000)),
),
)
.toList(),
),
);
}
// By default, show a loading spinner.
return Center(
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
),
);
},
)
]));
}
}
Model Class :
// To parse this JSON data, do
//
// final bannerModel = bannerModelFromJson(jsonString);
import 'dart:convert';
BannerModel bannerModelFromJson(String str) => BannerModel.fromJson(json.decode(str));
String bannerModelToJson(BannerModel data) => json.encode(data.toJson());
class BannerModel {
BannerModel({
required this.status,
required this.imgPath,
required this.banner,
});
int status;
String imgPath;
List<Banner> banner;
factory BannerModel.fromJson(Map<String, dynamic> json) => BannerModel(
status: json["status"],
imgPath: json["img_path"],
banner: List<Banner>.from(json["Banner"].map((x) => Banner.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"img_path": imgPath,
"Banner": List<dynamic>.from(banner.map((x) => x.toJson())),
};
}
class Banner {
Banner({
required this.id,
required this.type,
required this.parentId,
required this.title,
required this.caption,
required this.image,
required this.link,
required this.status,
required this.sliderOrder,
required this.entryTime,
});
String id;
String type;
String parentId;
String title;
String caption;
String image;
String link;
String status;
String sliderOrder;
DateTime entryTime;
factory Banner.fromJson(Map<String, dynamic> json) => Banner(
id: json["id"],
type: json["type"],
parentId: json["parent_id"],
title: json["title"],
caption: json["caption"],
image: json["image"],
link: json["link"],
status: json["status"],
sliderOrder: json["slider_order"],
entryTime: DateTime.parse(json["entry_time"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"type": type,
"parent_id": parentId,
"title": title,
"caption": caption,
"image": image,
"link": link,
"status": status,
"slider_order": sliderOrder,
"entry_time": entryTime.toIso8601String(),
};
}
If my understanding is correct, you want to show images in the Banner. So you should populate your imagesList like this:
List<String> imagesList = [];
snapshot.data!.banner.foreach((e) {
imagesList.add(snapshot.data!.imgPath+"/"+e.image);
});
eg:details about the questions....................................................................I have a model class Name is RasiphalaContent . i want to access main_img,title to display in home page. but not able to access in home page.below i've attached the model class and Home page code please find and check it.
Home Page:
import 'dart:io';
import 'dart:math';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'DetailsPage.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'Model/RasiphalaContent.dart';
var paddingBottom = 48.0;
var androidDeviceInfo;
var identifier;
var token;
var token1;
class HomePage extends StatelessWidget {
final String apiUrl = "https://www.sofikart.com/MobileApi/banners";
final String apiUrl1 =
"https://wayindia.net/indigo/odia_rashifal/rasifhala.php";
Future<RasiphalaContent> fetchData() async {
final response = await http.get(Uri.parse(apiUrl1));
print(response.body);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return RasiphalaContent.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ଆଜିର ରାଶିଫଳ'),
centerTitle: true,
),
body: Container(
child: FutureBuilder<RasiphalaContent>(
future: fetchData(),
builder: (BuildContext context, snapshot) {
final data = snapshot.data;
_getId();
if (snapshot.hasData) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 20,
mainAxisSpacing: 25,
),
padding: EdgeInsets.all(13),
shrinkWrap: true,
itemBuilder: (ctx, index) {
return InkWell(
child: Container(
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(Radius.circular(12))),
child: Column(
children: [
Expanded(
flex: 9,
child: ClipRRect(
borderRadius:
BorderRadius.all(Radius.circular(12)),
child: Image.network(,
fit: BoxFit.fill)),
),
Expanded(
flex: 2,
child: Text(
title(),
style: TextStyle(
color: Colors.black, fontSize: 17),
)),
],
),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailsPage(),
),
);
},
);
},
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
),
);
}
Future<String?> _getId() async {
identifier;
final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
if (Platform.isAndroid) {
// import 'dart:io'
var build = await deviceInfoPlugin.androidInfo;
identifier = build.androidId!; //UUID for Android
token = await FirebaseMessaging.instance.getToken();
token1 = await FirebaseMessaging.instance.getToken();
login();
}
}
login() async {
final response = await http.post(
"https://wayindia.net/indigo/odia_rashifal/device_create.php",
body: {
//"flag": 1.toString(),
"device_id": identifier,
"device_token": token,
});
final data = jsonDecode(response.body);
int value = data['status'];
String message = data['message'];
if (value == 1) {
print(message);
} else {
print("fail");
print(message);
}
}
}
Model Class :
// To parse this JSON data, do
//
// final rasiphalaContent = rasiphalaContentFromJson(jsonString);
import 'dart:convert';
RasiphalaContent rasiphalaContentFromJson(String str) => RasiphalaContent.fromJson(json.decode(str));
String rasiphalaContentToJson(RasiphalaContent data) => json.encode(data.toJson());
class RasiphalaContent {
RasiphalaContent({
required this.status,
required this.message,
required this.data,
});
int status;
String message;
List<Datum> data;
factory RasiphalaContent.fromJson(Map<String, dynamic> json) => RasiphalaContent(
status: json["status"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
required this.id,
required this.title,
required this.content,
required this.engTitle,
required this.mainImg,
required this.image2,
required this.image3,
required this.image4,
});
String id;
String title;
String content;
String engTitle;
String mainImg;
String image2;
String image3;
String image4;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
title: json["title"],
content: json["content"],
engTitle: json["eng_title"],
mainImg: json["main_img"],
image2: json["image_2"],
image3: json["image_3"],
image4: json["image_4"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"content": content,
"eng_title": engTitle,
"main_img": mainImg,
"image_2": image2,
"image_3": image3,
"image_4": image4,
};
}