How to remove an element from a http call? Flutter/Dart - flutter

hello I am doing a http request and I want to remove the elements which have some specific value, for example if 'region' is 'USA' I don't want to receive it.
here is my call:
Future fetch() async {
if (isLoading) return;
isLoading = true;
const limit = 10;
final url = Uri.parse('https://everywhere-dev.iccs.gr:18083/evse/getEvsesPaged?page=$page&pageLimit=$limit&lat=' +
(this.widget.appController.currentLocation != null ? this.widget.appController.currentLocation!.latitude : this.widget.appController.originalMapPoint.latitude).toString() + '&lon=' +
(this.widget.appController.currentLocation != null ? this.widget.appController.currentLocation!.longitude : this.widget.appController.originalMapPoint.longitude).toString());
final response = await http.get(url);
if (response.statusCode == 200) {
final List newItems = json.decode(response.body)["results"];
setState(() {
page++;
isLoading = false;
if (newItems.length <limit) {
hasMore = false;
}
tempEvses.addAll(newItems.map<Evse>((items) {
final evseID = items['evseID'];
final friendlyName = items['friendlyName'];
final street = items['street'];
final streetNumber = items['streetNumber'];
final region = items['region'];
final lat = items['lat'] ?? 0.0;
final lng = items['lng'] ?? 0.0;
final connectorList = items['connectorList'];
final cpSerial = items['cpSerial'];
final img = items['img'];
return new Evse(evseID: evseID, friendlyName: friendlyName, street: street, streetNumber: streetNumber, region: region, lat: lat, lng: lng, connectorList: [connectorList], cpSerial: cpSerial, img: img);
}).toList());
for(int i=0 ; i<tempEvses.length; i++ ){
this.tempEvses[i].calculateDistance(widget.appController.currentLocation);
// this.tempEvses[i].calculateAvailability();
this.tempEvses[i].isEvseFavorite(widget.appController.favoritesList);
this.tempEvses[i].storePlugCounters();
}
showEvsePanels();
});
}
}

If you don't want to receive certain values you must work on the API and not on the app.
Maybe you couldn't work on the API so the only way is to work on the data that your app received.
You should try newItems.removeWhere((item) => item['region'] == 'USA')

Change you map to this:
tempEvses.addAll(
newItems.map<Evse>(
(items) {
final evseID = items['evseID'];
final friendlyName = items['friendlyName'];
final street = items['street'];
final streetNumber = items['streetNumber'];
final region = items['region'];
final lat = items['lat'] ?? 0.0;
final lng = items['lng'] ?? 0.0;
final connectorList = items['connectorList'];
final cpSerial = items['cpSerial'];
final img = items['img'];
if (region != 'USA') {
return new Evse(
evseID: evseID,
friendlyName: friendlyName,
street: street,
streetNumber: streetNumber,
region: region,
lat: lat,
lng: lng,
connectorList: [connectorList],
cpSerial: cpSerial,
img: img);
}
},
).toList(),
);

Related

Flutter model json

How do I retrieve the information in the address? Attempted to retrieve information I can fetch but the Items class part is not fetching the address part. I'm practicing the fetch api.
I'm not sure if what I'm doing is correct. or may be stuck with some part of the problem i try to fix please help me
List<Items> _list = [];
List<Items> _search = [];
var loading = false;
Future fetchMos() async {
setState(() {
loading = true;
});
_list.clear();
var client = http.Client();
String mosUrl =
'';
var url = Uri.parse(mosUrl);
var headers = {'Client-Token': ''};
var response = await client.get(url, headers: headers);
if (response.statusCode == 200) {
var data = jsonDecode((utf8.decode(response.bodyBytes)))['items'];
setState(() {
for (Map i in data) {
_list.add(Items.fromJson(i));
loading = false;
}
});
}
}
This is class model
class Items {
String? custnum;
String? name;
List<Address>? address;
Items({this.custnum, this.name, this.address});
Items.fromJson(json) {
custnum = json['custnum'];
name = json['name'];
if (json['address'] != null) {
address = <Address>[];
json['address'].forEach((v) {
address!.add(new Address.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['custnum'] = this.custnum;
data['name'] = this.name;
if (this.address != null) {
data['address'] = this.address!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Address {
int? shipto;
String? addr1;
String? thanon;
String? tambon;
String? amphur;
String? provCode;
String? province;
String? country;
String? phone;
String? email;
String? postcode;
String? contact;
String? latitude;
String? longitude;
String? fax;
String? soi;
Address(
{this.shipto,
this.addr1,
this.thanon,
this.tambon,
this.amphur,
this.provCode,
this.province,
this.zipcode,
this.country,
this.phone,
this.email,
this.postcode,
this.contact,
this.latitude,
this.longitude,
this.fax,
this.soi});
Address.fromJson(json) {
shipto = json['shipto'];
addr1 = json['addr1'];
thanon = json['thanon'];
tambon = json['tambon'];
amphur = json['amphur'];
provCode = json['prov_code'];
province = json['province'];
zipcode = json['zipcode'];
country = json['country'];
phone = json['phone'];
email = json['email'];
postcode = json['postcode'];
contact = json['contact'];
latitude = json['latitude'];
longitude = json['longitude'];
fax = json['fax'];
soi = json['soi'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['shipto'] = this.shipto;
data['addr1'] = this.addr1;
data['thanon'] = this.thanon;
data['tambon'] = this.tambon;
data['amphur'] = this.amphur;
data['prov_code'] = this.provCode;
data['province'] = this.province;
data['zipcode'] = this.zipcode;
data['phone'] = this.phone;
data['email'] = this.email;
data['postcode'] = this.postcode;
data['contact'] = this.contact;
data['longitude'] = this.longitude;
data['fax'] = this.fax;
data['soi'] = this.soi;
return data;
}
}
var data =json.decode(response.body);
for (var i in data['items']) {
_list.add(Items.fromJson(i));
loading = false;
}
setState(() { });

How to calculate by road distance from one point to another in km from latitiude and longitude. Flutter

I actually need to calculate the distance from my current location to another location and i have the latitude and longitude of the two points. I want to get the road distance in km from my point(location) to another point. How can it be done.
Note: Not displacement.
Stuck with this for many days.
Use Google Distance Matrix API and enable Distance Matrix API from google cloud platform console.
void getDistanceAndDuration(LatLng origin, LatLng destination, ResponseCallback<DistanceDurationResponse?, String?> callback) async {
try {
var apiResponse = await _client.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins=${origin.latitude},${origin.longitude}"
"&destinations=${destination.latitude},${destination.longitude}&key=$mapApiKey&mode=DRIVING&",);
DistanceDurationResponse response = DistanceDurationResponse.fromJson(apiResponse.data);
var rows = response?.rows;
if(rows != null && rows.isNotEmpty) {
var elements = rows.first.elements;
if(elements != null && elements.isNotEmpty) {
var element = elements.first;
var duration = element.duration;
var distance = element.distance;
}
}
} on DioError catch (e) {
log(e.toString());
} on FormatException catch (e) {
log(e.toString());
} catch (e) {
log(e.toString());
}
}
_
class DistanceDurationResponse {
String? status;
List<Rows>? rows;
List<String>? originAddresses;
List<String>? destinationAddresses;
DistanceDurationResponse({
this.destinationAddresses,
this.originAddresses,
this.rows,
this.status,
});
DistanceDurationResponse.fromJson(dynamic json) {
destinationAddresses = json['destination_addresses'] != null ? json['destination_addresses'].cast<String>() : [];
originAddresses = json['origin_addresses'] != null ? json['origin_addresses'].cast<String>() : [];
if (json['rows'] != null) {
rows = [];
json['rows'].forEach((v) {
rows?.add(Rows.fromJson(v));
});
}
status = json['status'];
}
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['destination_addresses'] = destinationAddresses;
map['origin_addresses'] = originAddresses;
if (rows != null) {
map['rows'] = rows?.map((v) => v.toJson()).toList();
}
map['status'] = status;
return map;
}
}
class Rows {
List<DistanceDurationElement>? elements;
Rows({this.elements,});
Rows.fromJson(dynamic json) {
if (json['elements'] != null) {
elements = [];
json['elements'].forEach((v) {
elements?.add(DistanceDurationElement.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
if (elements != null) {
map['elements'] = elements?.map((v) => v.toJson()).toList();
}
return map;
}
}
class DistanceDurationElement {
String? status;
EstimatedDistance? distance;
EstimatedDuration? duration;
DistanceDurationElement({
this.distance,
this.duration,
this.status,
});
DistanceDurationElement.fromJson(dynamic json) {
distance = json['distance'] != null ? EstimatedDistance.fromJson(json['distance']) : null;
duration = json['duration'] != null ? EstimatedDuration.fromJson(json['duration']) : null;
status = json['status'];
}
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
if (distance != null) {
map['distance'] = distance?.toJson();
}
if (duration != null) {
map['duration'] = duration?.toJson();
}
map['status'] = status;
return map;
}
}
class EstimatedDuration {
int? value;
String? text;
EstimatedDuration({
this.text,
this.value,
});
EstimatedDuration.fromJson(dynamic json) {
text = json['text'];
value = json['value'];
}
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['text'] = text;
map['value'] = value;
return map;
}
}
class EstimatedDistance {
int? value;
String? text;
EstimatedDistance({
this.text,
this.value,
});
EstimatedDistance.fromJson(dynamic json) {
text = json['text'];
value = json['value'];
}
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['text'] = text;
map['value'] = value;
return map;
}
}
class GetDistanceWithPolyLines {
// Object for PolylinePoints
late PolylinePoints polylinePoints;
// List of coordinates to join
List<LatLng> polylineCoordinates = [];
// Map storing polylines created by connecting two
points
Map<PolylineId, Polyline> polylines = {};
// Create the polylines for showing the route between two
places
createPolylines(
double startLatitude,
double startLongitude,
double destinationLatitude,
double destinationLongitude,
) async {
// Initializing PolylinePoints
polylinePoints = PolylinePoints();
// Generating the list of coordinates to be used for
// drawing the polylines
PolylineResult result = await
polylinePoints.getRouteBetweenCoordinates(
'You api key', // Google
Maps API Key
PointLatLng(startLatitude, startLongitude),
PointLatLng(destinationLatitude, destinationLongitude),
travelMode: TravelMode.transit,
);
// Adding the coordinates to the list
if (result.points.isNotEmpty) {
result.points.forEach((PointLatLng point) {
polylineCoordinates.add(LatLng(point.latitude,
point.longitude));
});
}
return loopIt();
}
double _coordinateDistance(lat1, lon1, lat2, lon2) {
var p = 0.017453292519943295;
var c = cos;
var a = 0.5 -
c((lat2 - lat1) * p) / 2 +
c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p))
/ 2;
return 12742 * asin(sqrt(a));
}
double totalDistance = 0.0;
// Calculating the total distance by adding the distance
// between small segments
var _placeDistance;
loopIt() {
for (int i = 0; i < polylineCoordinates.length - 1;
i++) {
totalDistance += _coordinateDistance(
polylineCoordinates[i].latitude,
polylineCoordinates[i].longitude,
polylineCoordinates[i + 1].latitude,
polylineCoordinates[i + 1].longitude,
);
}
return _placeDistance = totalDistance.toStringAsFixed(2);
}
}

How to place markers dynamically from API to google map in flutter?

class LiveVehicleTrackingModel {
double lat;
double lng;
int speed;
double refDist;
String refLoc;
String accStatus;
String recDateTime;
String driver;
double temperature;
String imoblize;
LiveVehicleTrackingModel(
{this.lat,
this.lng,
this.speed,
this.refDist,
this.refLoc,
this.accStatus,
this.recDateTime,
this.driver,
this.temperature,
this.imoblize});
LiveVehicleTrackingModel.fromJson(Map<String, dynamic> json) {
lat = json['lat'];
lng = json['lng'];
speed = json['speed'];
refDist = json['refDist'];
refLoc = json['refLoc'];
accStatus = json['accStatus'];
recDateTime = json['recDateTime'];
driver = json['driver'];
temperature = json['temperature'];
imoblize = json['Imoblize'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['lat'] = lat;
data['lng'] = lng;
data['speed'] = speed;
data['refDist'] = refDist;
data['refLoc'] = refLoc;
data['accStatus'] = accStatus;
data['recDateTime'] = recDateTime;
data['driver'] = driver;
data['temperature'] = temperature;
data['Imoblize'] = imoblize;
return data;
}
}
// This is where i am getting location from the Api.
Future<List<LiveVehicleTrackingModel>> getLocations() async {
try {
var url = ApiConstants.liveTrackingApi;
final resp = await http.post(Uri.parse(url));
final responsebody = jsonDecode(resp.body);
return responsebody;
} catch (e) {
return [];
}
}
// This is the first question where i am loading locations with the help of model class.
// List locations = [];
LatLng latlng;
loadLocations() async {
List<LiveVehicleTrackingModel> locations;
locations = [];
locations = await getLocations(); //we store the response in a list
for (var i = 0; i < locations.length; i++) {
// LatLng latlng;
latlng = LatLng(
(locations[i].lat),
(locations[i].lng),
);
allMarkers.add(
Marker(
markerId: MarkerId(locations[i].accStatus.toString()),
position: latlng,
),
);
}
// setState(() {
//
// });
}
I have attached my model class and also the two functions through which i am fetching data from api. But the i am not able to place markers on map. Map just shows blank. Kindly help me out

Flutter | How to write a method to return List of String from a custom class model?

Class :
class Cart {
String id;
Product product;
String product_name;
double quantity;
List<Option> options;
String userId;
Cart();
Map toMap() {
var map = new Map<String, dynamic>();
map['product_name'] = product.name;
map["id"] = id;
map["quantity"] = quantity;
map["product_id"] = product.id;
map["price"] = product.price;
map["user_id"] = userId;
map["options"] = options.map((element) => element.id).toList();
map["userphone"] = currentUser.value.phone;
map["username"] = currentUser.value.name;
return map;
}
}
In the code above, map is returned as a type Cart. I want to convert that as a type of List & return in the same way when called. How can this be achieved ?
Expected output from the method as a dynamic value. This WHOLE value is going to be added to a List as an element at a specific position :
[product_name: coke, id: 22, quantity: 1.0, product_id: 139, price: 20.0, user_id: 138, options: [], userphone: 9898565621, username: jamie]
I created a sample map with string values for testing and here is the code,
var map = new Map<String, dynamic>();
map['product_name'] = 'product.name';
map["id"] = 'id';
map["quantity"] = 'quantity';
map["product_id"] = 'product.id';
map["price"] = 'product.price';
map["user_id"] = 'userId';
map["options"] = 'abc';
map["userphone"] = 'currentUser.value.phone';
map["username"] = 'currentUser.value.name';
var keys = map.keys.toList();
var values = map.values.toList();
List result = List();
int i = 0;
values.map((value){
result.add({keys[i] : values[i]});
i++;
}).toList();
print(result);
//you can return result here
you can make a list like this while calling API
http.Response response = await http.get(
EndPoint.Book,
);
if (response.statusCode == 200) {
var parsed = jsonDecode(response.body);
var bookData = parsed['books'];
List<Cart> cart= bookData.map<Cart>((e) => Cart.fromJson(e)).toList();
print(data);
return data;
}
and use https://javiercbk.github.io/json_to_dart/ or https://pub.dev/packages/json_serializable for making a data class.

How to authenticate the websocket in flutter

I am using Traccar but could not use websocket in Flutter as it is not providing any data.
I think websocket requires authentication or tokens to get the data.
class _HomeState extends State<Home> {
IOWebSocketChannel channel = IOWebSocketChannel.connect("ws://167.172.215.197:8082/api/socket");
#override
Widget build(BuildContext context) {
print(channel);
return new Scaffold(
resizeToAvoidBottomPadding: false,
appBar: AppBar(
title: Text('Map'),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// details(),
StreamBuilder(
stream: channel.stream,
builder: (context, snapshot) {
print(snapshot);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
child: Container(
child:
Column(
children: <Widget>[
Text(snapshot.hasData ? '${snapshot.data.positions}' : 'No Data'),
],
),
),
);
},
)
],
),
);
}
}
I want to receive the data from the server using websocket in flutter.
yes you need to authenticate and use some variables, for example:
String _cookie;
String _email = "your_email";
String _password = "your_password" ;
final _dio = Dio();
String _cookie;
String serverUrl = "your_server_ip";
StreamSubscription<dynamic> _rawPosSub;
final _devicesMap = <int, Device>{};
final _positions = StreamController<Device>.broadcast();
Future<void> _getConnection({String protocol = "http", String email, String password}) async {
final addr = "$protocol://$serverUrl/api/session";
Map<String, String> body = {
'email' : '$email',
'password': '$password',
};
final response = await Dio().post(addr, data: body,
options: new Options(contentType:"application/x-www-form-urlencoded"));
_cookie = response.headers["set-cookie"][0];
print(_cookie);
}
Next, you should need to create a Device Class (Don't forget to change the project name in the import line of utils)
import 'package:geopoint/geopoint.dart';
import 'package:your_project/utils/utils.dart';
/// A class representing a device
class Device {
/// Main constructor
Device(
{this.id,
this.uniqueId,
this.groupId,
this.name,
this.position,
this.batteryLevel,
this.keepAlive = 1,
this.isActive,
this.isDisabled,
this.properties = const <String, dynamic>{}});
/// The device database id
final int id;
/// The on device unique id
String uniqueId;
/// The group of the device
int groupId;
/// The device name
String name;
/// The device position
DevicePosition position;
/// The device battery level
double batteryLevel;
/// Minutes a device is considered alive
int keepAlive;
/// The device can be disabled
bool isDisabled;
/// false if the device has never updated one position
bool isActive;
/// Extra properties for the device
Map<String, dynamic> properties;
/// Is the device online
bool get isAlive => _isDeviceAlive();
/// Create a device from json data
Device.fromPosition(Map<String, dynamic> data,
{String timeZoneOffset = "0", int keepAlive = 1})
: this.keepAlive = keepAlive,
this.id = int.parse(data["deviceId"].toString()),
this.position =
DevicePosition.fromJson(data, timeZoneOffset: timeZoneOffset),
this.batteryLevel =
double.parse(data["attributes"]["batteryLevel"].toString());
bool _isDeviceAlive() {
if (position == null) {
return false;
}
final now = DateTime.now();
final dateAlive = now.subtract(Duration(minutes: keepAlive));
bool isAlive = false;
if (position.date.isAfter(dateAlive)) {
isAlive = true;
}
return isAlive;
}
/// Print a description of the device
void describe() {
print("Device:");
print(" - id : $id");
print(" - uniqueId : $uniqueId");
print(" - name : $name");
print(" - batteryLevel: $batteryLevel");
print(" - position : $position");
}
#override
String toString() {
String _name = "$uniqueId";
if (name != null) {
_name = name;
}
String res;
if (position != null) {
res = "$_name: $position";
} else {
res = "$_name";
}
return res;
}
}
/// A class to handle a device position
class DevicePosition {
/// The position database id
final int id;
/// The geo data
final GeoPoint geoPoint;
/// The distance since previous point
final double distance;
/// The total distance for the device
final double totalDistance;
/// The address of the device position
final String address;
/// The date of the position
DateTime date;
/// Create a position from json
DevicePosition.fromJson(Map<String, dynamic> data,
{String timeZoneOffset = "0"})
: this.id = int.parse(data["id"].toString()),
this.geoPoint = GeoPoint(
name: data["id"].toString(),
latitude: double.parse(data["latitude"].toString()),
longitude: double.parse(data["longitude"].toString()),
speed: double.parse(data["speed"].toString()),
accuracy: double.parse(data["accuracy"].toString()),
altitude: double.parse(data["altitude"].toString())),
this.distance = double.parse(data["attributes"]["distance"].toString()),
this.totalDistance =
double.parse(data["attributes"]["totalDistance"].toString()),
this.address = data["address"].toString() {
this.date = dateFromUtcOffset(data["fixTime"].toString(), timeZoneOffset);
}
#override
String toString() {
return "$date : ${geoPoint.latitude}, ${geoPoint.longitude}";
}
}
Also you should use a utils method
/// parse a date
DateTime dateFromUtcOffset(String dateStr, String timeZoneOffset) {
DateTime d = DateTime.parse(dateStr);
if (timeZoneOffset.startsWith("+")) {
final of = int.parse(timeZoneOffset.replaceFirst("+", ""));
d = d.add(Duration(hours: of));
} else if (timeZoneOffset.startsWith("-")) {
final of = int.parse(timeZoneOffset.replaceFirst("-", ""));
d = d.subtract(Duration(hours: of));
}
return d;
}
Finally you should need the following methods to listen positions:
/// Get the device positions
Future<Stream<Device>> positions() async {
final posStream =
await _positionsStream(serverUrl: serverUrl, email: _email, password: _password);
_rawPosSub = posStream.listen((dynamic data) {
print("DATA $data");
final dataMap = json.jsonDecode(data.toString()) as Map<String, dynamic>;
if (dataMap.containsKey("positions")) {
DevicePosition pos;
for (final posMap in dataMap["positions"]) {
//print("POS MAP $posMap");
pos = DevicePosition.fromJson(posMap as Map<String, dynamic>);
final id = posMap["deviceId"] as int;
Device device;
if (_devicesMap.containsKey(id)) {
device = _devicesMap[id];
} else {
device = Device.fromPosition(posMap as Map<String, dynamic>,
keepAlive: 1);
}
device.position = pos;
_devicesMap[id] = device;
_positions.sink.add(device);
}
} else {
for (final d in dataMap["devices"]) {
if (!_devicesMap.containsKey(d["id"])) {
final id = int.parse(d["id"].toString());
d["name"] ??= d["id"].toString();
final device = Device(id: id, name: d["name"].toString());
_devicesMap[id] = device;
//print(" - ${device.name}");
}
}
}
});
return _positions.stream;
}
Future<Stream<dynamic>> _positionsStream(
{String serverUrl, String email, String password, String protocol = "http"}) async {
if (_cookie == null) {
await _getConnection(email: _email, password: _password);
}
final channel = IOWebSocketChannel.connect("ws://$serverUrl/api/socket",
headers: <String, dynamic>{"Cookie": _cookie});
return channel.stream;
}
When you finish, you can call
_init() async {
_getConnection(email: _email, password: _password);
final pos = await positions();
print("Listening for position updates");
pos.listen((device) {
print("POSITION UPDATE: $device");
print("${device.id}: ${device.position.geoPoint.latitude} / " +
"${device.position.geoPoint.longitude}");
});
}
Also I use these dependences and flutter version 1.17.0 stable:
dio: ^3.0.9
web_socket_channel:
geopoint: ^0.7.1
Note: I use code from traccar_client 0.1.0 and modify it to access from email and password, but if you need to use the token, you can follow the example from
https://github.com/synw/traccar_client. The credits are to them. :)