I want to show my data from my API postman to flutter, and I already succeed to get my data with printed it on my terminal, but I cannot show my data in my emulator.
I have this error:
Exception has occurred._TypeError (type 'String' is not a subtype of type 'int' of 'index')
My error is in value like value: data[index]['kode'] and value: data[index]['nama']
This is my code:
product.dart
class _pageSuccessState extends State<pageSuccess> {
var data;
Future<void> getUserApi() async {
final response = await http.get(
Uri.parse('http://10.0.2.2:8000/api/produk'),
headers: headersWithToken,
);
var encodeFirst = json.encode(response.body.toString());
if (response.statusCode == 200) {
data = jsonDecode(encodeFirst).toString();
print(data);
print('product success');
} else {
print('product failed');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Api Course'),
),
body: Column(
children: [
Expanded(
child: FutureBuilder(
future: getUserApi(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Text('Loading');
} else {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return Card(
child: Column(
children: [
ReusbaleRow(
title: 'kode',
value: data[index]['kode'].toString(),
),
ReusbaleRow(
title: 'nama',
value: data[index]['nama'].toString(),
),
],
),
);
});
}
},
),
)
],
),
);
}
}
class ReusbaleRow extends StatelessWidget {
String title;
String value;
ReusbaleRow({Key? key, required this.title, required this.value})
: super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(title as String),
Text(value as String),
],
),
);
}
}
Your var called for parameter 'itemCounter' in your widget ListView is a String type. Replaces there a List variable or an int value.