I'm using CarouselSlider package and the items I used is from a hardcoded data. I'd like to get data from mapping it from a List<Object>
. Here is my object:
final List<Object> imgListObject = [
{"image": "/imageAsset1", "text": 'Text 1'},
{"image": "/imageAsset2", "text": 'Text 2'},
{"image": "/imageAsset3", "text": 'Text 3'},
];
And this is how I intend to get the data:
final List<Widget> imageSliders = imgListObject
.map(
(data) => Column(
children: [
Image.asset(data['image']),
Text(data['text']),
],
),
)
.toList();
I have this error from data['image']
and data['text']
:
The operator '[]' isn't defined for the type 'Object'.
My full code:
class HowItWorksScreen extends StatelessWidget {
const HowItWorksScreen({super.key});
@override
Widget build(BuildContext context) {
ContentSession contentSession = Provider.of<ContentSession>(context, listen: false);
final CarouselController _carouselController = CarouselController();
final List<Object> imgListObject = [
{"image": AppGlobalVariables.howItWorksSliderImage1, "text": 'Text 1'},
{"image": AppGlobalVariables.howItWorksSliderImage2, "text": 'Text 2'},
{"image": AppGlobalVariables.howItWorksSliderImage3, "text": 'Text 3'},
];
final List<Widget> imageSliders = imgListObject
.map(
(data) => Column(
children: [
Image.asset(data['image']),
Text(data['text']),
],
),
)
.toList();
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppbarMain(),
),
body: Column(
children: [
CarouselSlider(
carouselController: _carouselController,
options: CarouselOptions(
viewportFraction: 0.8,
enableInfiniteScroll: true,
enlargeCenterPage: true,
autoPlay: true,
height: 400,
),
items: imageSliders,
),
SizedBox(
height: 40,
),
ElevatedButton(
onPressed: () async => Navigator.pushNamed(context, landingScreenRoute!),
child: Text(contentSession.stringsHomeScreen.signin),
),
],
),
);
}
}
The problem is obvious:
final List<Object> imgListObject = [
{"image": "/imageAsset1", "text": 'Text 1'},
{"image": "/imageAsset2", "text": 'Text 2'},
{"image": "/imageAsset3", "text": 'Text 3'},
];
is a List
of Object
's, so when you later call:
Column(
children: [
Image.asset(data['image']),
Text(data['text']),
],
it can't access data['image']
since it thinks it's an Object
not a Map
.
You'll have to explicitly cast the type. you can do so using the as
keyword:
final List<Widget> imageSliders = imgListObject.map(
(item) {
Map<String, String> data = item as Map<String, String>;
return Column(
children: [
// using the `!` operator to assert that the value is not null
Image.asset(data['image']!),
Text(data['text']!),
],
);
},
).toList();
Or as an alternative, specify the correct type for imgListObject
:
final List<Map<String, String>> imgListObject = [
{"image": "/imageAsset1", "text": 'Text 1'},
{"image": "/imageAsset2", "text": 'Text 2'},
{"image": "/imageAsset3", "text": 'Text 3'},
];