I want to fetch and print datas from this json file :
[{"id": "76d751584e134ebf854bebda8998334b", "data": {"timestamp": "15/05/2021-13:08:38", "temperature": 21.9, "pressure": 1007.4342535, "humidity": 43.994442131}}, {"id": "6188e169eeda4547b3e87414d50664df", "data": {"timestamp": "15/05/2021-15:08:38", "temperature": 22.28, "pressure": 1006.47539066, "humidity": 46.1434366089}}, {"id": "4eb75a12fd6c4eb8a94b20106aab4e2a", "data": {"timestamp": "15/05/2021-17:08:38", "temperature": 22.71, "pressure": 1006.52941164, "humidity": 47.7676641555}}]
This is my flutter code witch is supposed to do the job :
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class SensorData with ChangeNotifier {
//final id;
final timestamp;
final temperature;
final pressure;
final humidity;
SensorData({
//@required this.id,
@required this.timestamp,
@required this.temperature,
@required this.pressure,
@required this.humidity,
});
factory SensorData.fromJson(Map<String, dynamic> json) {
return new SensorData(
//id: json['id'] as String,
timestamp: json['timestamp'] as String,
temperature: json['temperature'] as double,
pressure: json['pressure'] as double,
humidity: json['humidity'] as double,
);
}
}
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
Future<List<SensorData>> fetchSensorDatas() async {
final http.Response response = await http.get(Uri.http(<my_API_url>));
var responseJson = json.decode(response.body);
return (responseJson['data'] as List)
.map((p) => SensorData.fromJson(p))
.toList();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: new Container(
child: new Column(
children: [
new Container(
height: 200,
),
new ListView(
children: <Widget>[
new FutureBuilder<List<SensorData>>(
future: fetchSensorDatas(),
builder: (context, snapshot) {
if (snapshot.hasData){
List<SensorData> posts = snapshot.data;
return new Column(
children: posts.map((post) => new Column(
children: <Widget>[
new Text(post.temperature),
],
)).toList()
);
}
else if(snapshot.hasError)
{
return snapshot.error;
}
return new Center(
child: new Column(
children: <Widget>[
new Padding(padding: new EdgeInsets.all(50.0)),
new CircularProgressIndicator(),
],
),
);
},
),
],
),
],
),
),
);
}
}
I have 2 errors :
- snapshot.data returns me "A value of type 'List?' can't be assigned to a variable of type 'List'."
- snapshot.error returns me "The return type 'Object?' isn't a 'Widget', as required by the closure's context.".
Where am I getting wrong?
Many thanks in advance!!