'Flutter Api Data fetching Error with typeCast and asynchronous suspension
I'm trying to fetch the API Data , and it's just returned Circular Progress Indicator when I'm checking my response body from the client Im receiving my required but was unable to display it. Kindly guide me through it where Im going wrong. My Data from API looks like this I just want to access id and distance
[
{
"id": 1,
"messageId": null,
"distance": "39",
"partitionId": "1",
"eventProcessedUtcTime": "2022-02-08T10:48:12.81",
"eventEnqueuedUtcTime": "2022-02-08T10:47:38.21",
"ioThub": "{\"MessageId\":null,\"CorrelationId\":null,\"ConnectionDeviceId\":\"iotwmcs-esp32\",\"ConnectionDeviceGenerationId\":\"637798347400200573\",\"EnqueuedTime\":\"2022-02-08T10:47:38.2060000Z\"}"
}
]
This is my file where I'm fetching data
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/models/ilmcs_info.dart';
import 'package:http/http.dart' as http;
class UpperLevelTankData extends StatefulWidget {
const UpperLevelTankData({Key key}) : super(key: key);
@override
_UpperLevelTankDataState createState() => _UpperLevelTankDataState();
}
class _UpperLevelTankDataState extends State<UpperLevelTankData> {
StreamController<IotWmcsModel> _streamController = StreamController();
@override
void dispose() {
_streamController.close();
}
@override
void initState() {
super.initState();
Timer.periodic(const Duration(seconds: 3), (timer) {
fetchApiData();
});
}
Future<IotWmcsModel> fetchApiData() async {
var url = Uri.parse(
'https://iotwmcsapi20220208180616.azurewebsites.net/api/Iotwmcsta004');
final response = await http.get(url);
final dataBody = json.decode(response.body).first;
// print(dataBody);
IotWmcsModel iotWmcsModel = IotWmcsModel.fromJson(dataBody);
_streamController.sink.add(iotWmcsModel);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<IotWmcsModel>(
stream: _streamController.stream,
builder: (context, snapdata) {
switch (snapdata.connectionState) {
case ConnectionState.waiting:
return const CircularProgressIndicator();
default:
if (snapdata.hasError) {
return const Text('Please Wait....');
} else {
return buildIotWmcsWidget(snapdata.data);
}
}
},
);
}
Widget buildIotWmcsWidget(IotWmcsModel iotWmcsModel) {
print("${iotWmcsModel.distance}");
return Text(
"${iotWmcsModel.distance}".toString(),
style: const TextStyle(
color: Colors.white, fontSize: 25, fontWeight: FontWeight.w900),
);
}
}
this is the model of my data
class IotWmcsModel {
final int distance;
final int id;
IotWmcsModel({this.distance, this.id});
factory IotWmcsModel.fromJson(Map<String, dynamic> json) {
return IotWmcsModel(
distance: json['distance'] as int, id: json['id'] as int);
}
Map<String, dynamic> toJson() => {
'distance': distance,
'id': id,
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
