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),
),
],
),
);
}
}
2
Answers
The problem is obvious:
is a
List
ofObject
‘s, so when you later call:it can’t access
data['image']
since it thinks it’s anObject
not aMap
.You’ll have to explicitly cast the type. you can do so using the
as
keyword:Or as an alternative, specify the correct type for
imgListObject
:See also
What does the "as" keyword do in Dart language?
The operator '[]' isn't defined for the class 'Object'. Dart
Here’s another way to extract that, with patterns: