I'm trying to get a flutter api result. The fact is that the tutorial I was following shows how to receive a JSON list and how to analyze it, but I need to know how to receive a certain data from the API and make a condition to handle this data, I need to know if I find the snippet ( ignition: true) the car's trip is active, the car is moving if (ignition: false) the car has reached the end of the trip, it's stopped, I even know the logic I need to do but I don't know how to analyze it from JSON. Below is the code I'm working on, I'm stuck.
As soon as I'm reading the data:
class DetailPage extends StatelessWidget {
final Car user;
var travels = [];
DetailPage(this.user);
Future<List<Position>> _getCarros() async {
var data = await http.get(
"http://www15.itrack.com.br/vehicles/${user.id}/positions");
var jsonData = json.decode(data.body);
List<Position> carros = [];
for (var u in jsonData) {
Position carro = Position(
u["id"],
u["vehicleId"],
u["datetime"],
u["latitude"],
u["longitude"],
u["address"],
u["ignition"],
u["hodometro"]);
carros.add(carro);
}
print(carros.length);
return carros;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(user.name),
),
body: Container(
child: FutureBuilder(
future: _getCarros(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
print(snapshot.data);
if (snapshot.data == null) {
return Container(child: Center(child: Text("Loading...")));
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int id) {
return Card(
child: ListTile(
title: Text(snapshot.data[id].ignition.toString()),
subtitle: Text(snapshot.data[id].hodometro.toString()),
),
);
},
);
}
},
),
),
);
And that was the function I did in javascript but I don't know how to do it in dart (I'm new to flutter)
var positionInicial = null
var travels = []
for(var i =0; i < positions.size; i++){
if(positionInicial == null && positions[i].ignition == true){
positionInicial = positions[i]
}
if(positionInicial != null && positions[i].ignition == false){
travels.push(trave{initial: positionInital.id, final: positions[i].id})
positionInicial = null
}
}
This is the API for the trips of a given vehicle in this case with id = 1.
{
"id": 1,
"vehicleId": 1,
"datetime": 1612455145422,
"latitude": -19.915,
"longitude": -43.945,
"address": "Rua V01, P01 - Centro",
"ignition": true,
"hodometro": 120000
},
{
"id": 2,
"vehicleId": 1,
"datetime": 1612455205422,
"latitude": -19.915,
"longitude": -43.945,
"address": "Rua V01, P02 - Centro",
"ignition": true,
"hodometro": 120100
},
{
"id": 3,
"vehicleId": 1,
"datetime": 1612455265422,
"latitude": -19.915,
"longitude": -43.945,
"address": "Rua V01, P03 - Centro",
"ignition": false,
"hodometro": 120200
},
{
"id": 4,
"vehicleId": 1,
"datetime": 1612455325422,
"latitude": -19.915,
"longitude": -43.945,
"address": "Rua V01, P04 - Centro",
"ignition": false,
"hodometro": 120300
},
{
"id": 5,
"vehicleId": 1,
"datetime": 1612455385422,
"latitude": -19.915,
"longitude": -43.945,
"address": "Rua V01, P05 - Centro",
"ignition": true,
"hodometro": 120400
},
{
"id": 6,
"vehicleId": 1,
"datetime": 1612455445422,
"latitude": -19.915,
"longitude": -43.945,
"address": "Rua V01, P06 - Centro",
"ignition": false,
"hodometro": 120500
},
{
"id": 7,
"vehicleId": 1,
"datetime": 1612455505422,
"latitude": -19.915,
"longitude": -43.945,
"address": "Rua V01, P07 - Centro",
"ignition": true,
"hodometro": 120600
}
Result:
- Position1: ignition - on
- Position2: ignition - on
- Position3: ignition - off
- Position4: ignition - off
- Position5: ignition - on
- Position6: ignition - off
- Position7: ignition - on
Final:
- Travel1: Position1 à Position3
- Travel2: Position5 à Position6
- Travel3: Position7
Solution 1: Ουιλιαμ Αρκευα
CODE UPDATED (02-03-2021)
NetService
class NetService {
static Future<T> getJson<T>(String url) {
return http.get(Uri.parse(url))
.then((response) {
if (response.statusCode == 200) {
return jsonDecode(response.body) as T;
}
print('Status Code : ${response.statusCode}...');
return null;
})
.catchError((err) => print(err));
}
}
Main
import 'dart:io';
import 'package:_samples2/networking.dart';
class Travel {
static const baseUrl = 'http://www15.itrack.com.br/recruitmentpositionapi/vehicles';
var data = [];
void fetchPositions() async {
var id = 1;
var flag = true;
print('Start fetching...');
await Future.doWhile(() async {
await NetService
.getJson<List>('$baseUrl/$id/positions')
.then((response) {
response != null && response.isNotEmpty
? data.addAll(response)
: flag = false;
})
.whenComplete(() {
print('Fetching done for ID $id...');
id++;
});
return flag;
});
print('Job done!\n');
}
void listPositions() {
data.forEach((m) => print('Position ${m['id']} : ignition - ${m['ignition'] ? 'on' : 'off'}'));
print('');
}
void listTravels() {
var points = data.map((m) => [m['id'], m['ignition']]).toList();
var journeys = <List<int>>[];
void calculateJourney([int from = 0]) {
if (from != null && from >= 0) {
int start, stop;
start = points.indexWhere((e) => e[1], from);
if (start >= 0) stop = points.indexWhere((e) => !e[1], start);
journeys.add([start, stop]);
calculateJourney(stop);
}
}
calculateJourney();
for (var i = 0; i < journeys.length; i++) {
stdout.write('Travel ${i+1} : Position ${points[journeys[i][0]][0]}');
journeys[i][1] >= 0
? print(' to Position ${points[journeys[i][1]][0]}')
: print('');
}
}
}
void main(List<String> args) async {
var travel = Travel();
await travel.fetchPositions();
travel
..listPositions()
..listTravels();
}
Result:
Start fetching...
Fetching done for ID 1...
Fetching done for ID 2...
Fetching done for ID 3...
Fetching done for ID 4...
Fetching done for ID 5...
Job done!
Position 1 : ignition - on
Position 2 : ignition - on
Position 3 : ignition - off
Position 4 : ignition - off
Position 5 : ignition - on
Position 6 : ignition - off
Position 7 : ignition - on
Position 8 : ignition - off
Position 9 : ignition - on
Position 10 : ignition - on
Position 11 : ignition - on
Position 12 : ignition - on
Position 13 : ignition - off
Position 14 : ignition - on
Position 15 : ignition - on
Position 16 : ignition - on
Position 17 : ignition - off
Position 18 : ignition - off
Position 19 : ignition - off
Position 20 : ignition - off
Position 21 : ignition - off
Position 22 : ignition - on
Position 23 : ignition - on
Position 24 : ignition - on
Position 25 : ignition - on
Travel 1 : Position 1 to Position 3
Travel 2 : Position 5 to Position 6
Travel 3 : Position 7 to Position 8
Travel 4 : Position 9 to Position 13
Travel 5 : Position 14 to Position 17
Travel 6 : Position 22