I am new to flutter programming and I am trying to create a program based on a tutorial. My code does not have errors but when I run it, it throws an error type 'String' is not a subtype of type 'int' of 'index'. This is my code. I think the error lies on the rows.
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';
class Readings {
final int id;
final double temperature, humidity;
final String FanStatus, MistStatus;
final DateTime Time;
Readings(
{required this.id,
required this.temperature,
required this.humidity,
required this.FanStatus,
required this.MistStatus,
required this.Time});
factory Readings.fromJson(Map<String,dynamic> json) {
return Readings(
id: json['id'],
temperature: json['temperature'],
humidity: json['humidity'],
FanStatus: json['FanStatus'],
MistStatus: json['MistStatus'],
Time: json['Time'],
);
}
}
Future<List<Readings>> fetchSummary() async {
final response = await http.get(Uri.parse('http://mushroomdroid.online/dbscript-1.php'));
if (response.statusCode == 200) {
var parsed = json.decode(response.body);
// print(parsed.length);
List jsonResponse = parsed["id"] as List;
return jsonResponse.map((job) => Readings.fromJson(job)).toList();
} else {
print('Error, Could not load Data.');
throw Exception('Failed to load Data');
}
}
class RecordsPage extends StatefulWidget {
const RecordsPage({Key? key}) : super(key: key);
@override
_RecordsPage createState() => _RecordsPage();
}
class _RecordsPage extends State<RecordsPage> {
final controller = ScrollController();
double offset = 0;
late Future<List<Readings>> _func;
@override
void initState() {
_func = fetchSummary();
controller.addListener(onScroll);
super.initState();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
void onScroll() {
setState(() {
offset = (controller.hasClients) ? controller.offset : 0;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<Readings>>(
future: _func,
builder: (ctx, snapshot) {
if (snapshot.hasData) {
List<Readings>? data = snapshot.data;
// print(data);
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Center(
child: Text('Worldwide Cases ->'),
),
Padding(
padding: EdgeInsets.only(top:10.0
),
child: Center(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
sortColumnIndex: 0,
sortAscending: true,
columns: [
DataColumn(
label: Text(
'Country',
style: TextStyle(
fontSize: 18.0,
),
),
numeric: false,
tooltip: "Country Name",
),
DataColumn(
label: Text(
'Total Confirmed',
style: TextStyle(
color: Colors.orange.shade900,
fontSize: 16.0,
),
),
numeric: true,
tooltip: "Total Confirmed",
),
DataColumn(
label: Text(
'New Confirmed',
style: TextStyle(
fontSize: 16.0,
),
),
numeric: true,
tooltip: "New Confirmed",
),
DataColumn(
label: Text(
'Total Deaths',
style: TextStyle(
color: Colors.red.shade700,
fontSize: 16.0,
),
),
numeric: true,
tooltip: "Total Deaths",
),
DataColumn(
label: Text(
'New Deaths',
style: TextStyle(
fontSize: 16.0,
),
),
numeric: true,
tooltip: "New Deaths",
),
DataColumn(
label: Text(
'Total Recovered',
style: TextStyle(
color: Colors.green,
fontSize: 16.0,
),
),
numeric: true,
tooltip: "Total Recovered",
),
DataColumn(
label: Text(
'New Recovered',
style: TextStyle(
fontSize: 16.0,
),
),
numeric: true,
tooltip: "New Recovered",
),
],
rows: data!
.map(
(country) => DataRow(
cells: [
DataCell(
SizedBox(
width: 100,
child: Text(
country.id.toString(),
softWrap: true,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.w600),
),
),
),
DataCell(
SizedBox(
width: 60.0,
child: Center(
child: Text(
country.Time.toString(),
style: TextStyle(
fontWeight: FontWeight.bold),
),
),
),
),
DataCell(
Center(
child: Text(
country.temperature.toString(),
style: TextStyle(
fontWeight: FontWeight.bold),
),
),
),
DataCell(
Center(
child: Text(
country.humidity.toString(),
style: TextStyle(
fontWeight: FontWeight.bold),
),
),
),
DataCell(
Center(
child: Text(
country.FanStatus.toString(),
style: TextStyle(
fontWeight: FontWeight.bold),
),
),
),
DataCell(
Center(
child: Text(
country.MistStatus.toString(),
style: TextStyle(
fontWeight: FontWeight.bold),
),
),
),
],
),
)
.toList(),
),
),
),
),
// SizedBox(height: 500),
],
),
);
} else if (snapshot.hasError) {
return AlertDialog(
title: Text(
'An Error Occured!',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.redAccent,
),
),
content: Text(
"${snapshot.error}",
style: TextStyle(
color: Colors.blueAccent,
),
),
actions: <Widget>[
TextButton(
child: Text(
'Go Back',
style: TextStyle(
color: Colors.redAccent,
),
),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
}
// By default, show a loading spinner.
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(height: 20),
Text('This may take some time..')
],
),
);
},
),
);
}
}
This is the tutorial I am learning from:
https://github.com/Dhruvpolaris/covid-19_project/blob/master/lib/widgets/details_screen.dart
Please help me. Thank you in advance.
CodePudding user response:
I ran into this same issue while working with Firebase, in my case a field in the Firebase console had int instead of a string. In your case, the issue could be this piece here
List jsonResponse = parsed["id"].toString() as List;
CodePudding user response:
Please check Below code.
class Readings {
String? id;
String? temperature;
String? humidity;
String? fanStatus;
String? mistStatus;
String? time;
Readings(
{this.id,
this.temperature,
this.humidity,
this.fanStatus,
this.mistStatus,
this.time});
Readings.fromJson(Map<String, dynamic> json) {
id = json['id'];
temperature = json['temperature'];
humidity = json['humidity'];
fanStatus = json['FanStatus'];
mistStatus = json['MistStatus'];
time = json['Time'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['temperature'] = this.temperature;
data['humidity'] = this.humidity;
data['FanStatus'] = this.fanStatus;
data['MistStatus'] = this.mistStatus;
data['Time'] = this.time;
return data;
}
}
Method code
Future<List<Readings>> fetchSummary() async {
final response = await http.get(Uri.parse('http://mushroomdroid.online/dbscript-1.php'));
if (response.statusCode == 200) {
var data = response.body.replaceAll('\r\n', '\\r\\n');
var parsed = json.decode(data);
return parsed;
} else {
print('Error, Could not load Data.');
throw Exception('Failed to load Data');
}
}