I’m in the process of learning the Carousel widget in Flutter, and I understand how to upload images using assets folder directly.
However, now I am having trouble not knowing how to proceed with displaying images in a Carousel using file paths stored in a local JSON file.
A snippet of the JSON file given below, where the data I wanted to show is under “carousel_path”:
[
{
"name": "Desi Vibes",
"cuisine": "Indian, Mughlai, North Indian",
"address": "1st Floor, G-50, Maharaja Agrasen Marg, Opposite McDonald's, G Block, Pocket G, Sector 18, Noida, Uttar Pradesh 201301, India",
"latitude": 28.5701,
"longitude": 77.3210,
"rating": 3.0,
"image_path": "assets/images/desi_vibes.JPG",
"carousel_path":
{
"path1" : "assets/images/desi_vibes/desi1.JPG",
"path2" : "assets/images/desi_vibes/desi2.JPG",
"path3" : "assets/images/desi_vibes/desi3.JPG",
"path4" : "assets/images/desi_vibes/desi-vibes.jpg"
}
]
Following is the code where I have loaded images directly from Assets. I want to use the file paths stored in JSON to load images.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
final List<String> imagePaths = [
"assets/images/concept.jpg",
"assets/images/lamborghini.jpg",
"assets/images/mercedes.jpg"
];
late List<Widget> _pages;
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
_pages = List.generate(
imagePaths.length,
(index) => ImagePlaceHolder(
imagePath: imagePaths[index],
));
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: const Text('Page View Tutorial')),
body: Column(
children: [
SizedBox(
width: double.infinity,
height: MediaQuery.of(context).size.height / 4,
child: PageView.builder(
itemCount: imagePaths.length,
itemBuilder: (context, index) {
return _pages[index];
}),
),
],
)),
);
}
}
class ImagePlaceHolder extends StatelessWidget {
final String? imagePath;
const ImagePlaceHolder({super.key, this.imagePath});
@override
Widget build(BuildContext context) {
return Image.asset(
imagePath!,
fit: BoxFit.cover,
);
}
}
I am having trouble figuring out how to proceed. Any help will be appreciated.