I am trying to fetch data from a table named Collections in a local MySql database. The Code is as under:
class CollectionsPage extends StatefulWidget {
@override
_CollectionsPageState createState() => _CollectionsPageState();
}
class _CollectionsPageState extends State<CollectionsPage> {
Future<List<dynamic>> fetchData() async {
final response = await http.get(Uri.parse('http://10.0.2.2/myDashFolder/collections_fetch.php'));
if (response.statusCode == 200) {
try {
final jsonData = jsonDecode(response.body);
print(response.body);
if (jsonData is List<dynamic>) {
print(response.body);
return jsonData;
}
} catch (e) {
print('Failed to decode JSON: $e');
}
}
return [];
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<dynamic>>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
return Flexible(
fit: FlexFit.loose,
child:ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
final collection = snapshot.data![index];
return ListTile(
title: Text(collection['ProjectName'] ?? ''),
subtitle: Text(collection['TransactionDate'] ?? ''),
);
},
)
);
} else {
return Text('No data available');
}
},
);
}
}
The first print statement works but the second doesn't. Please help me solve this.
I was trying to show the fethced data but nothing is displayed on the screen.
Your response print(response.body);
is most likely not a valid list of maps of strings.
With a hardcoded valid response like the following it works as expected:
final jsonData = jsonDecode("[{\"ProjectName\" : \"first\", \"TransactionDate\" : \"1\"}]");
In relation to your latest comment with an example result of
{"status":"success" ,"result":[
{"Id":"2","TransactionDate":"2020-11-02","ProjectName":"Rove","FromName":"Tejaswi","ToName":"Amita","Amount":"100000","Narration":"Given to Amita"},
{"Id":"3","TransactionDate":"2020-11-02","ProjectName":"Rove","FromName":"Amita","ToName":"Others","Amount":"100000","Narration":"Murram filling through Shakti Vellimaran"}
]}
you receive a Map<String, dynamic>
instead where you probably want to access the "result" list.
So you have to change your if to:
if (jsonData is Map<String, dynamic> && jsonData["result"] is List<dynamic>) {
final List<dynamic> result = jsonData["result"] as List<dynamic>;
print(result);
return result;
}