Hello i have one question i was fetching categories from api which works fine in postman but on flutter i didn't use model class just using dio i need to fetch this json api as an array for top bar vertical scroll of categories.
here is my postman response
{
"data": [
{
"id": 1,
"name": "Electronics",
"color": "#ff8000"
},
{
"id": 2,
"name": "SpareParts",
"color": "#00ff40"
},
]
}
and in flutter i used
getCatagories() async {
var tokens;
var dioo = Dio();
dioo.interceptors
.add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
var customHeaders = {
'content-type': 'application/json',
};
options.headers.addAll(customHeaders);
return options;
}));
var response = await dioo.get("https://www.mywebiste.com/api/cat");
if(response.data.isEmpty||response.data==null)
{
}
else
{
}
return response.data;
}
to fetch these catagories i have used
List categories = [];
@override
void initState() {
getCatagories().then((data) {
setState(() {
categories = data;
});
});
super.initState();
}
// by default first item will be selected
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: kDefaultPadding / 2),
height: 30,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: categories.length,
itemBuilder: (context, index) => GestureDetector(
onTap: () {
Fluttertoast.showToast(
msg: "This is Center Short Toast"+selectedIndex.toString(),
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
setState(() {
selectedIndex = index;
});
},
child: Container(
alignment: Alignment.center,
margin: EdgeInsets.only(
left: kDefaultPadding,
// At end item it add extra 20 right padding
right: index == categories.length - 1 ? kDefaultPadding : 0,
),
padding: EdgeInsets.symmetric(horizontal: kDefaultPadding),
decoration: BoxDecoration(
color: index == selectedIndex
? Colors.white.withOpacity(0.4)
: Colors.transparent,
borderRadius: BorderRadius.circular(6),
),
child: Text(
categories[index],
style: TextStyle(color: Colors.white),
),
),
),
),
);
}
so when i run these app categories will not appear for scrollbar and error is Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List
You are getting the data from request as Map and assigning it to List. you should make categories as Map:
Note: don't give it generics.
after that you will have some problems in the code below while looping in the categories. That's another question. :)