Flutter : Image not showing in CarouselSlider...? - flutter

eg: details about the questions ......................................................I've implemented CarouselSlider to make a banner in home page. I've debug from my mobile data is coming correct but image not showing. Below I've mentioned the model class and home page please find and check.
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(),
};
}
Home Page :-
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:newbharatbiz/VendorRegistrationPage.dart';
import 'dart:convert';
import 'NavDrawer.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'Model Class/banner_model.dart';
var paddingBottom = 48.0;
var androidDeviceInfo;
var identifier;
var token = "debendra";
var token1;
class HomePage extends StatelessWidget {
final String bannerAPI =
"https://newbharatbiz.in/mobile_api/v4/all_banner.php";
Future<BannerModel> fetchAlbum() async {
final response = await http.get(Uri.parse(bannerAPI));
print(response.body);
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');
}
}
late DateTime currentBackPressTime;
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.deepOrangeAccent,
child: Icon(Icons.add),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VendorRegistrationPage(),
),
);
},
),
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) {
List<String> imagesList = [];
print(imagesList);
snapshot.data!.banner.forEach((e) {
imagesList.add(snapshot.data!.imgPath + e.image);
});
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),
),
),
);
},
)
]));
}
Future<bool> onWillPop() {
DateTime now = DateTime.now();
if (currentBackPressTime == null ||
now.difference(currentBackPressTime) > Duration(seconds: 2)) {
currentBackPressTime = now;
return Future.value(false);
}
return Future.value(true);
}
}

Related

Unhandled Exception: Failed host lookup:

I created project to look for sports stadiums in my town. It gets all data from website's Swagger API, data like addresses, price, images and names.
Swagger host: http://admin.sports.com.kg/swagger/
I created ApiRemote to get data from swagger host. It worked perfectly first week, but later it returned exception. Maybe it's because of http.
Terminal returns this error:
E/flutter (26867): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Failed host lookup: 'admin.sports.com.kg'
It says it has an exception in this line:
var responses = await client.get(uri);
import 'dart:async';
import 'dart:convert';
import 'package:untitled/models/post.dart';
import 'package:http/http.dart' as http;
class RemoteService {
Future<List<Result>?> getPosts() async {
List<Result> list;
var client = http.Client();
var uri = Uri.parse('http://admin.sports.com.kg/api/sports_areas');
var responses = await client.get(uri);
if (responses.statusCode == 200) {
final parsed = json.decode(responses.body) as Map<String, dynamic>;
list = parsed['results'].map<Result>((e) =>Result.fromJson(e)).toList();
print(parsed['results']);
// final p = Post.fromJson(parsed);
// list.add(p);
return list;
}
}
}
Post file that contains all data from Swagger
import 'dart:convert';
Post postFromJson(String str) => Post.fromJson(json.decode(str));
String postToJson(Post data) => json.encode(data.toJson());
class Post {
Post({
required this.next,
this.previous,
required this.count,
required this.pageSize,
required this.numPages,
required this.results,
});
int next;
dynamic previous;
int count;
int pageSize;
int numPages;
List<Result> results;
factory Post.fromJson(Map<String, dynamic> json) => Post(
next: json["next"],
previous: json["previous"],
count: json["count"],
pageSize: json["page_size"],
numPages: json["num_pages"],
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"next": next,
"previous": previous,
"count": count,
"page_size": pageSize,
"num_pages": numPages,
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
Result({
required this.id,
required this.title,
required this.price,
required this.address,
required this.image,
});
int id;
String title;
int price;
String address;
String image;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
title: json["title"],
price: json["price"],
address: json["address"],
image: json["image"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"price": price,
"address": address,
"image": image,
};
}
Main Page class
class _HomePageState extends State<HomePage> {
int _selind = 0;
List<Result>? _stadiums;
var isLoaded = false;
#override
void initState() {
super.initState();
getData();
}
void getData() async {
_stadiums = (await RemoteService().getPosts()) as List<Result>?;
if (_stadiums != null) {
setState(() {
isLoaded = true;
});
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.indigo[50],
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 30),
child: Visibility(
visible: isLoaded,
child: ListView.builder(
itemCount: _stadiums?.length,
itemBuilder: (context, index) {
return Column(
// child: _widgetopt.elementAt(_selind),
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
children: [
Image.network(_stadiums![index].image),
Text('Sportclubs "${_stadiums![index]
.title}"', textDirection: TextDirection.ltr,
style: TextStyle(fontSize: 20,
fontWeight: FontWeight.bold),),
Row(
children: [
Icon(Icons.location_on_outlined,
color: Colors.redAccent, size: 40,),
Text(_stadiums![index].address),
],
)
]
),
),
SizedBox(
height: 10,
),
],
);
}),
replacement: Center(child: CircularProgressIndicator()),
),
),),);
}
}

Flutter : Carousel image not showing?

eg: details about the questions ......................................................I've implemented CarouselSlider to make a banner in home page. I've debug from my mobile data is coming correct but image not showing. Below I've mentioned the model class and home page please find and check.
Home Page:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:newbharatbiz/Screens/VendorRegistrationPage.dart';
import 'dart:convert';
import '../Utils/NavDrawer.dart';
import 'package:carousel_slider/carousel_slider.dart';
import '../Model Class/banner_model.dart';
import 'SearchServiceProvider.dart';
var paddingBottom = 48.0;
var androidDeviceInfo;
var identifier;
var token = "debendra";
var token1;
final String bannerAPI = "https://newbharatbiz.in/mobile_api/v4/all_banner.php";
class HomePage extends StatelessWidget {
Future<BannerModel> fetchAlbum() async {
final response = await http.get(Uri.parse(bannerAPI));
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');
}
}
late DateTime currentBackPressTime;
List<String> imagesList = [];
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.deepOrangeAccent,
child: Icon(Icons.add),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VendorRegistrationPage(),
),
);
},
),
drawer: NavDrawer(),
appBar:
AppBar(title: Text('New Bharat Biz'), centerTitle: true, actions: [
IconButton(
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SearchServiceProvider(),
),
);
},
icon: Icon(Icons.search),
),
]),
body: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
FutureBuilder<BannerModel>(
future: fetchAlbum(),
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
print((snapshot.data));
snapshot.data?.banner.forEach((e) {
imagesList.add(snapshot.data!.imgPath + e.image);
});
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),
),
),
);
},
)
]));
}
Future<bool> onWillPop() {
DateTime now = DateTime.now();
if (currentBackPressTime == null ||
now.difference(currentBackPressTime) > Duration(seconds: 2)) {
currentBackPressTime = now;
return Future.value(false);
}
return Future.value(true);
}
}
future builders require return type widget but you forget to add the return keyword in your slider widget just add the return keyword and it will work.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
var paddingBottom = 48.0;
var androidDeviceInfo;
var identifier;
var token = "debendra";
var token1;
final String bannerAPI = "https://newbharatbiz.in/mobile_api/v4/all_banner.php";
class HomePages extends StatelessWidget {
Future<BannerModel> fetchAlbum() async {
final response = await http.get(Uri.parse(bannerAPI));
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');
}
}
late DateTime currentBackPressTime;
List<String> imagesList = [];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
FutureBuilder<BannerModel>(
future: fetchAlbum(),
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
print((snapshot.data));
snapshot.data?.banner.forEach((e) {
imagesList.add(snapshot.data!.imgPath + e.image);
print(imagesList.length);
});
return CarouselSlider( //add return keyword here
options: CarouselOptions(
height: 330,
aspectRatio: 16 / 9,
viewportFraction: 0.8,
initialPage: 0,
enableInfiniteScroll: true,
reverse: false,
autoPlay: true,
autoPlayInterval: const Duration(seconds: 3),
autoPlayAnimationDuration: const Duration(milliseconds: 800),
autoPlayCurve: Curves.fastOutSlowIn,
enlargeCenterPage: true,
),
items: imagesList
.map(
(item) => Center(
child: Image.network(item,
fit: BoxFit.cover, width: 1000)),
)
.toList(),
);
}
return const Center(
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
),
);
}
// By default, show a loading spinner.
)
]));
}
}
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(),
};
}
// 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(),
};
}

Flutter :- Issues in model i've accessed img_path but not able to access image because want to concatenate (img_path+image) to display in home page?

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);
});

Flutter: Not able to access main_img,title from model?

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,
};
}

Flutter. When I fetch data from API showing StatusCode 403(Failed to load post)?

eg: details about the questions ..........................................................................
When I want to fetch multiple objects from an array showing status code 403(Failed to load post).and API having a header key I have implemented it also. but showing failed to load post status code 403.
{
"status": 1,
"msg": "7 banners found",
"data": [
{
"id": "14",
"image": "https://www.sofikart.com/admin/upload/app_banner/1635945056.jpeg",
"cat_id": "4",
"product_id": "81",
"url": null,
"status": "Active",
"ordering": "0",
"updated": "2021-11-03 06:10:56"
},
{
"id": "7",
"image": "https://www.sofikart.com/admin/upload/app_banner/1642082634.jpeg",
"cat_id": "4",
"product_id": "111",
"url": null,
"status": "Active",
"ordering": "1",
"updated": "2021-10-28 04:53:26"
}
]
}
controller
-----------
import 'dart:io';
import 'package:fm_sidharth/model/post.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
final String url = 'https://www.sofikart.com/MobileApi/banners';
Future<List<Post>> fetchPost() async {
final response = await http.get(
url, headers: {HttpHeaders.authorizationHeader: 'SOFIKART-*2021#',},);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
final result = json.decode(response.body);
List<Post> posts =
result.map<Post>((model) => new Post.fromJson(model)).toList();
return posts;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
Future<String> saveNetworkImageToPhoto(String url, String title,
{bool useCache: true}) async {
var data = await getNetworkImageData(url, useCache: useCache);
var filePath = await ImagePickerSaver.saveFile(fileData: data, title: title);
return filePath;
}
class ImagePickerSaver {
static saveFile({fileData, String title}) {}
}
getNetworkImageData(String url, {booluseCache, bool
useCache}) {
}
model
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
Post welcomeFromJson(String str) => Post.fromJson(json.decode(str));
String welcomeToJson(Post data) => json.encode(data.toJson());
class Post {
Post({
this.status,
this.msg,
this.data,
});
int status;
String msg;
List<Datum> data;
factory Post.fromJson(Map<String, dynamic> json) => Post(
status: json["status"],
msg: json["msg"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
String get catId => null;
get image => null;
Map<String, dynamic> toJson() => {
"status": status,
"msg": msg,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.id,
this.image,
this.catId,
this.productId,
this.url,
this.status,
this.ordering,
this.updated,
});
String id;
String image;
String catId;
String productId;
dynamic url;
String status;
String ordering;
DateTime updated;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
image: json["image"],
catId: json["cat_id"],
productId: json["product_id"],
url: json["url"],
status: json["status"],
ordering: json["ordering"],
updated: DateTime.parse(json["updated"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"image": image,
"cat_id": catId,
"product_id": productId,
"url": url,
"status": status,
"ordering": ordering,
"updated": updated.toIso8601String(),
};
}
home
import 'package:flutter/material.dart';
import 'package:fm_sidharth/Controller/postController.dart';
import 'package:fm_sidharth/model/post.dart';
import 'package:fm_sidharth/page/postdetails.dart';
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<List<Post>> posts;
_HomePageState() {
posts = fetchPost();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: FutureBuilder<List<Post>>(
future: posts,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return FlatButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PostDetails(snapshot.data[index])),
);
},
child: Card(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
snapshot.data[index].catId,
style: TextStyle(
color: Colors.black,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
),
SizedBox(
height: 10,
),
FadeInImage.assetNetwork(
image: snapshot.data[index].image,
placeholder: 'assets/images/noimage.png',
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
IconButton(
icon: Icon(Icons.favorite_border),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.share),
onPressed: () {
},
),
IconButton(
icon: Icon(Icons.save),
onPressed: () {
saveNetworkImageToPhoto(
snapshot.data[index].image,snapshot.data[index].catId).then((value){
});
},
),
],
)
],
),
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return Center(child: CircularProgressIndicator());
},
),
);
}
}
I have this error too some times, I think this about restrict that google set on you country. please use a proxy. I hope my answer helping to you :)