How to authenticate the websocket in flutter - 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. :)

Related

flutter : display current user information flutter [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 16 days ago.
Improve this question
i try to display user info like email and user name in profile page , how to get user data for current user
i used flutter , php , mysql , thats my code :
1- login controller
abstract class LoginController extends GetxController {
// late TextEditingController phone;
late TextEditingController password;
late TextEditingController username;
LoginData loginData = LoginData(Get.find());
late StatusRequiest statusRequiest;
bool isShowPassword = true;
GlobalKey<FormState> formstate = GlobalKey<FormState>();
toSignUp();
toForgetPassword();
login();
showPassword() {
isShowPassword = isShowPassword == true ? false : true;
update();
}
}
class LoginControllerImp extends LoginController {
#override
login() async {
var formdata = formstate.currentState;
if (formdata!.validate()) {
statusRequiest = StatusRequiest.loading;
var response = await loginData.postdata(username.text,password.text); //getData from "Data folder" not "controller folder"
// if (kDebugMode) {
// print("===================== $response");
// }
statusRequiest = handlingData(response);
if (StatusRequiest.success == statusRequiest) {
if (response["status"] == "success") {
// data.addAll(response['data']);
Get.offAllNamed(AppRoutes.navbar);
// print(response);
} else {
Get.defaultDialog(title: "99".tr, middleText: "110".tr);
statusRequiest = StatusRequiest.faliure;
}
}
update();
// Get.offAllNamed(AppRoutes.verviyCodeSignUp);
} else {
if (kDebugMode) {
print('wrong');
}
}
}
#override
toSignUp() {
Get.toNamed(AppRoutes.signUp);
}
#override
toForgetPassword() {
Get.toNamed(AppRoutes.forgetPassword);
}
#override
void onInit() {
// phone = TextEditingController();
password = TextEditingController();
username = TextEditingController();
super.onInit();
}
#override
void dispose() {
// phone.dispose();
username.dispose();
password.dispose();
super.dispose();
}
}
2- json :
class UserModel {
String? userId;
String? userName;
String? userImage;
String? userCreate;
UserModel({
this.userId,
this.userName,
this.userImage,
this.userCreate,
});
UserModel.fromJson(Map<String, dynamic> json) {
userId = json['user_id'];
userName = json['user_name'];
userImage = json['user_image'];
userCreate = json['user_create'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['user_id'] = userId;
data['user_name'] = userName;
data['user_image'] = userImage;
data['user_create'] = userCreate;
return data;
}
}
3-
class LoginData {
Crud crud;
LoginData(this.crud);
postdata(String username, String password) async {
var response = await crud.postData(AppLink.login, {
"username": username,
// "phone": phone,
"password": password,
});
return response.fold((l) => l, (r) => r);
}
}
4-profile controller
abstract class ProfileController extends GetxController {
initialData();
getdata();
// goToItems(List categories, int selectedCat, String categoryid);
// goToDetails(List items, int selecteditems, String itemsid);
}
class ProfileControllerImp extends ProfileController {
MyServices myServices = Get.find();
String? username;
// String? email;
String? id;
ProfileData homeData = ProfileData(Get.find());
List users=[];
late StatusRequiest statusRequiest;
#override
initialData() {
username = myServices.sharedPreferences.getString("username");
id = myServices.sharedPreferences.getString("id");
}
#override
void onInit() {
getdata();
initialData();
super.onInit();
}
#override
getdata() async {
statusRequiest = StatusRequiest.loading;
var response = await homeData.getData(); //getData from "Data folder" not "controller folder"
statusRequiest = handlingData(response);
if (StatusRequiest.success == statusRequiest) {
// SharedPreferences sharedPreferences = SharedPreferences;
if (response['status'] == "success") {
users.addAll(response['users']);
print(users);
// items.addAll(response['items']);
if (kDebugMode) {
print(response);
}
} else {
statusRequiest = StatusRequiest.faliure;
}
}
update();
}
}
5-profile page
class Profile extends GetView<ProfileControllerImp> {
final UserModel? usermodel;
const Profile({super.key, this.usermodel});
#override
Widget build(BuildContext context) {
Get.put(ProfileControllerImp());
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
// automaticallyImplyLeading: false,
title: Text(
// '${usermodel?.userName}',
'118'.tr,
style: const TextStyle(color: Colors.black),
),
// actions: [],
centerTitle: true,
elevation: 0,
),
body: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount:2,
itemBuilder: (context, index) {
return SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: Text(controller.username!),
anyone can help plz
in php website and html i used to use $_session['username'] but here in flutter i dont know how to save in seesion , if you can solve this problem in same way plz help and thnx
use your user model, as i can see you areastoraging the data of the user in a class called User so you can use this same class to acces that data in the profile controller in the line
users.addAll(response['users']);
you create a list of user so you have to acces to the index of the list that contains the data of the user and instead of $_sesion["username"] you can use .username for example if you wanna show the data of the first user of the list you can do this:
users[0].name;
and thats equivalent to: $_sesion["username"]

flutter, how to compare the argument passed (id) equal an element.id ? using getx package

I have Categories, and each category contains multiple and different subcategories.
I passed the Id of Categories to the other screen.
First Screen:
onTap: (() => Get.to(const CategoryDetails(), arguments: {
"id":" ${categoriesController.cat!.elementAt(i).sId.toString()} ", })),
ArgumentController
import 'package:get/get.dart';
class ArgumentController extends GetxController {
String? id;
#override
void onInit() {
id = Get.arguments['id'];
super.onInit();
}
}
View File
class _CategoryDetailsState extends State<CategoryDetails> {
int selectedCategoryIndex = 0;
CategoriesController categoriesController = Get.put(CategoriesController());
#override
void initState() {
super.initState();
categoriesController.getCategoriesFromApi();
}
#override
Widget build(BuildContext context) {
ArgumentController controller = Get.put(ArgumentController());
debugPrint(controller.id);
return Scaffold(
appBar: AppBar(
title: const Text("Category Details"),
),
body: Column(
children: [
Text("${controller.id}"),
const Text("data"),
ListView.builder(itemBuilder: (context, index) {
return Column(
children: [
Text(categoriesController.cat!
.elementAt(index)
.subcategories!
.elementAt(selectedCategoryIndex)
.name
.toString()),
],
);
})
],
),
);
}
}
Controller file:
import 'dart:convert';
import 'dart:io';
import 'package:get/get.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import '../model/categoriesmodel.dart' as categories_model;
class CategoriesController extends GetxController {
Iterable<categories_model.Response>? cat;
var isDataLoading = false.obs;
getCategoriesFromApi() async {
try {
isDataLoading(true);
http.Response response = await http.post(
Uri.tryParse('-----')!,
headers: {
HttpHeaders.authorizationHeader: '-------',
});
if (response.statusCode == 200) {
var result = jsonDecode(response.body);
cat = categories_model.Categories.fromJson(result).response;
} else {}
} catch (e) {
debugPrint("Error while getting Data $e");
} finally {
isDataLoading(false);
}
}
}
Categoriesmodel file
class Categories {
String? status;
List<Response>? response;
Categories({this.status, this.response});
Categories.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['response'] != null) {
response = <Response>[];
json['response'].forEach((v) {
response!.add(Response.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['status'] = status;
if (response != null) {
data['response'] = response!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Response {
String? sId;
String? name;
bool? isForAccessories;
String? slug;
List<void>? liveTranslations;
String? icon;
String? logo;
int? itemsCount;
String? lang;
List<Subcategories>? subcategories;
Response(
{this.sId,
this.name,
this.isForAccessories,
this.slug,
this.liveTranslations,
this.icon,
this.logo,
this.itemsCount,
this.lang,
this.subcategories});
Response.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
isForAccessories = json['isForAccessories'];
slug = json['slug'];
// if (json['liveTranslations'] != null) {
// liveTranslations = <Null>[];
// json['liveTranslations'].forEach((v) {
// liveTranslations!.add(Null.fromJson(v));
// });
// }
icon = json['icon'];
logo = json['logo'];
itemsCount = json['itemsCount'];
lang = json['lang'];
if (json['subcategories'] != null) {
subcategories = <Subcategories>[];
json['subcategories'].forEach((v) {
subcategories!.add(Subcategories.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['_id'] = sId;
data['name'] = name;
data['isForAccessories'] = isForAccessories;
data['slug'] = slug;
// if (liveTranslations != null) {
// data['liveTranslations'] =
// liveTranslations!.map((v) => v.toJson()).toList();
// }
data['icon'] = icon;
data['logo'] = logo;
data['itemsCount'] = itemsCount;
data['lang'] = lang;
if (subcategories != null) {
data['subcategories'] =
subcategories!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Subcategories {
String? sId;
String? name;
bool? isForAccessories;
String? slug;
List<void>? liveTranslations;
int? itemsCount;
String? lang;
Subcategories(
{this.sId,
this.name,
this.isForAccessories,
this.slug,
this.liveTranslations,
this.itemsCount,
this.lang});
Subcategories.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
isForAccessories = json['isForAccessories'];
slug = json['slug'];
// if (json['liveTranslations'] != null) {
// liveTranslations = <Null>[];
// json['liveTranslations'].forEach((v) {
// liveTranslations!.add(Null.fromJson(v));
// });
// }
itemsCount = json['itemsCount'];
lang = json['lang'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['_id'] = sId;
data['name'] = name;
data['isForAccessories'] = isForAccessories;
data['slug'] = slug;
// if (liveTranslations != null) {
// data['liveTranslations'] =
// liveTranslations!.map((v) => v.toJson()).toList();
// }
data['itemsCount'] = itemsCount;
data['lang'] = lang;
return data;
}
}
The problem is in selectedCategoryIndex, how to express that
selectedCategoryIndex == categoriesController.Where((element) => element.sid == the argument passed);
note that it's not acceptable categoriesController.Where..
I just assumed your question to be what I think and posting this solution.
selectedCategoryIndex ==
categoriesController.cat.singleWhere((element) => element.id == id).sId;

Parsing json to model fails in flutter

I am trying to show data to listview but it doesn't show anything.there is json below ,am i doing something wrong,i tired to print the data in api call but i can print the data but not in the listview,
i having hardtime to understand what i doing wrong or correct.please help me on this
if (response.statusCode == 200) {
try {
if (status == true) {
var company_list = value['doc'];
for (int i = 0; i < company_list.length; i++) {
print(company_list);
var mobile_list = company_list["mobile"];
var email_list = company_list["email"];
company_model.add(CompanyModel.fromJson(company_list,mobile_list,email_list));
}
setState(() {
print("UI Updated");
});
} else {
final snackBar = SnackBar(content: Text(message));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} catch (e) {
e.toString();
}
} else {
final snackBar = SnackBar(content: Text(message));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
Json
{
"status":true,
"doc":{
"mobile":[
"9961256754",
"8974525672"
],
"email":[
],
"_id":"5f3a0dfe88b9d50453e92133",
"name":"MRC Labour",
"terms":{
"english":"We Shall not be liable for any disputes arising between the users and the
labourers",
"malayalam":"We Shall not be liable for any disputes arising between the users and the
labourers"
}
}
}
Model
class CompanyModel {
String id = "";
String mobile = "";
String email = "";
String name = "";
String english = "";
String malayalam = "";
CompanyModel({this.id, this.mobile, this.email, this.name, this.english,this.malayalam});
CompanyModel.fromJson(json,mobile_list,email_list)
: id = json['_id'].toString(),
mobile = mobile_list,
email = email_list,
name = json['name'].toString(),
english = json['terms']['english'].toString(),
malayalam = json['terms']['malayalam'].toString();
}
When the debugger hit at this line it breaks without any errors company_model.add(CompanyModel.fromJson(data,mobile_list,email_list));
This is listview code
Container(
height: 80,
width: 100,
color: Colors.blueGrey[100],
padding: EdgeInsets.all(10),
child: ListView.separated(
separatorBuilder: (BuildContext context, int index) =>
const Divider(),
itemCount: company_model.length,
itemBuilder: (BuildContext context, int index) {
CompanyModel data = company_model[index];
print(data);
return Container(
height: 10,
color: Colors.green,
child: Text(data.name.toString(),style: TextStyle(color: Colors.black),),
);
},
),
),
First of all, your model is wrong, you're parsing a List (mobile and email) as a String in your model, also, you don't really need to pass 2 additional parameters to the function.
class CompanyModel {
List<String> mobile;
List<String> email;
String sId;
String name;
Terms terms;
CompanyModel({this.mobile, this.email, this.sId, this.name, this.terms});
CompanyModel.fromJson(Map<String, dynamic> json) {
mobile = json['mobile'].cast<String>();
email = json['email'].cast<String>();
sId = json['_id'];
name = json['name'];
terms = json['terms'] != null ? new Terms.fromJson(json['terms']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['mobile'] = this.mobile;
data['email'] = this.email;
data['_id'] = this.sId;
data['name'] = this.name;
if (this.terms != null) {
data['terms'] = this.terms.toJson();
}
return data;
}
}
class Terms {
String english;
String malayalam;
Terms({this.english, this.malayalam});
Terms.fromJson(Map<String, dynamic> json) {
english = json['english'];
malayalam = json['malayalam'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['english'] = this.english;
data['malayalam'] = this.malayalam;
return data;
}
}
Also, double check that you're initializing the company_model as something like: List company_model = [] otherwise it initialize as null and won't work the rest of your code.
if (response.statusCode == 200) {
try {
if (status == true) {
var company_json = value['doc'];
company_model.add(CompanyModel.fromJson(company_json));
setState(() {
print("UI Updated");
});
} else {
final snackBar = SnackBar(content: Text(message));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} catch (e) {
e.toString();
}
} else {
final snackBar = SnackBar(content: Text(message));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
The best way to create model is in the link below
https://app.quicktype.io/
just put your json on as input on left side and select dart as language from left, you are good to go.

Parse JSON in flutter, show data in label

i have this json:
[
{
"id": 988846211,
"serviceTag": "1LJVKS2",
"orderBuid": 1212,
"shipDate": "2019-04-11T00:00:00Z",
"productCode": ";E403",
"localChannel": "ENTP",
"productId": "dell-u2719d-monitor",
"productLineDescription": "DELL ULTRASHARP U2719D",
"productFamily": "Unknown",
"systemDescription": "Dell U2719D",
"productLobDescription": "Displays",
"countryCode": "SE",
"duplicated": false,
"invalid": false,
"entitlements": [
{
"itemNumber": "709-15308",
"startDate": "2019-04-11T00:00:00Z",
"endDate": "2022-04-11T23:59:59.999Z",
"entitlementType": "INITIAL",
"serviceLevelCode": "ND",
"serviceLevelDescription": "C, NBD ONSITE",
"serviceLevelGroup": 5
},
{
"itemNumber": "865-41964",
"startDate": "2019-04-11T00:00:00Z",
"endDate": "2023-04-11T23:59:59.999Z",
"entitlementType": "INITIAL",
"serviceLevelCode": "ND",
"serviceLevelDescription": "C, NBD ONSITE",
"serviceLevelGroup": 5
}
]
}
]
and my main :
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:dell_warranty/dellTok.dart';
import 'package:dell_warranty/model_json.dart';
void main() => runApp(new MaterialApp(
home: new DellW(),
));
class DellW extends StatefulWidget {
#override
DellWState createState() => new DellWState();
}
class DellWState extends State<DellW> {
TextEditingController serviceTagg = TextEditingController();
final String getToken = "https://apigtwb2c.us.dell.com/auth/oauth/v2/token";
final String apiUrl =
"https://apigtwb2c.us.dell.com/PROD/sbil/eapi/v5/asset-entitlements";
String tagg;
DellTok dellTok;
ModelJson modelJson;
String disc = "";
List<ModelJson> data = [];
#override
void initState() {
super.initState();
this.checkDell();
}
checkDell() async {
var responseToken = await http.post(Uri.encodeFull(getToken), body: {
"grant_type": "client_credentials",
"client_id": "SECRET",
"client_secret": "SECRET"
});
if (responseToken.statusCode == 200) {
var responseTok = json.decode(responseToken.body);
dellTok = DellTok.fromJson(responseTok);
print(responseTok);
setState(() {});
} else {
print(responseToken.statusCode);
}
}
checkDellTagg(String serviceTag) async {
var queryParameters = {
'access_token': dellTok.accessToken,
'servicetags': serviceTag,
};
var uri = Uri.https('apigtwb2c.us.dell.com',
'/PROD/sbil/eapi/v5/asset-entitlements', queryParameters);
var responseDell = await http.get(uri, headers: {});
if (responseDell.statusCode == 200) {
List<dynamic> responseD = jsonDecode(responseDell.body);
List<ModelJson> modelJsonRes =
responseD.map((responseD) => ModelJson.fromJson(responseD)).toList();
setState(() {
disc = modelJson.productLineDescription;
});
} else {
print(responseDell.statusCode);
}
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Dell Warranty"),
),
body: dellTok == null
? Center(
child: CircularProgressIndicator(),
)
: Container(
padding: EdgeInsets.all(20.0),
child: Column(
children: [
RaisedButton(
onPressed: () => checkDellTagg(serviceTagg.text),
child: Text(
"Flat Button",
)),
TextField(
decoration:
InputDecoration(hintText: "write servicetag..."),
controller: serviceTagg,
),
Text(disc),
],
)));
}
}
and my model_json.dart file :
class ModelJson {
int id;
String serviceTag;
int orderBuid;
String shipDate;
String productCode;
String localChannel;
String productId;
String productLineDescription;
String productFamily;
String systemDescription;
String productLobDescription;
String countryCode;
bool duplicated;
bool invalid;
List<Entitlements> entitlements;
ModelJson(
{this.id,
this.serviceTag,
this.orderBuid,
this.shipDate,
this.productCode,
this.localChannel,
this.productId,
this.productLineDescription,
this.productFamily,
this.systemDescription,
this.productLobDescription,
this.countryCode,
this.duplicated,
this.invalid,
this.entitlements});
ModelJson.fromJson(Map<String, dynamic> json) {
id = json['id'];
serviceTag = json['serviceTag'];
orderBuid = json['orderBuid'];
shipDate = json['shipDate'];
productCode = json['productCode'];
localChannel = json['localChannel'];
productId = json['productId'];
productLineDescription = json['productLineDescription'];
productFamily = json['productFamily'];
systemDescription = json['systemDescription'];
productLobDescription = json['productLobDescription'];
countryCode = json['countryCode'];
duplicated = json['duplicated'];
invalid = json['invalid'];
if (json['entitlements'] != null) {
entitlements = new List<Entitlements>();
json['entitlements'].forEach((v) {
entitlements.add(new Entitlements.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['serviceTag'] = this.serviceTag;
data['orderBuid'] = this.orderBuid;
data['shipDate'] = this.shipDate;
data['productCode'] = this.productCode;
data['localChannel'] = this.localChannel;
data['productId'] = this.productId;
data['productLineDescription'] = this.productLineDescription;
data['productFamily'] = this.productFamily;
data['systemDescription'] = this.systemDescription;
data['productLobDescription'] = this.productLobDescription;
data['countryCode'] = this.countryCode;
data['duplicated'] = this.duplicated;
data['invalid'] = this.invalid;
if (this.entitlements != null) {
data['entitlements'] = this.entitlements.map((v) => v.toJson()).toList();
}
return data;
}
}
class Entitlements {
String itemNumber;
String startDate;
String endDate;
String entitlementType;
String serviceLevelCode;
String serviceLevelDescription;
int serviceLevelGroup;
Entitlements(
{this.itemNumber,
this.startDate,
this.endDate,
this.entitlementType,
this.serviceLevelCode,
this.serviceLevelDescription,
this.serviceLevelGroup});
Entitlements.fromJson(Map<String, dynamic> json) {
itemNumber = json['itemNumber'];
startDate = json['startDate'];
endDate = json['endDate'];
entitlementType = json['entitlementType'];
serviceLevelCode = json['serviceLevelCode'];
serviceLevelDescription = json['serviceLevelDescription'];
serviceLevelGroup = json['serviceLevelGroup'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['itemNumber'] = this.itemNumber;
data['startDate'] = this.startDate;
data['endDate'] = this.endDate;
data['entitlementType'] = this.entitlementType;
data['serviceLevelCode'] = this.serviceLevelCode;
data['serviceLevelDescription'] = this.serviceLevelDescription;
data['serviceLevelGroup'] = this.serviceLevelGroup;
return data;
}
}
I'm trying to show the data in text field .
everthing ok when i post to get an access token and its saved and i used it to make a get req to the other url so i can get the data.
example :
i want to show
productLineDescription
in text widget.
but im not going any farther than that!
how i am supposed to get data from model_json.dart and show it inside text widget?
sorry i am flutter newbie, thanks for the help.
If you want to get the productLineDescription, you have to call it like this:
productLineDescription = jsonDecode(myJson)[0]['productLineDescription'];
NOTE: myJson is your json source file.
You need the [0] because your json is inside a List.

Can't access values from redux state event hough I have an instance of the class

I have some state that is added during some middleware. This state is used to build ListTiles for a ListView. I cannot access the properties of this instance when I map over the instance.
I can see the info in the debugger: https://imgur.com/a/YTpjBou
But I cannot access the property because it returns null. I am unsure if this is because the future has not completed by the time it renders or what.
Here is the build for the home_widget
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
import 'package:nasp_portal_app/model/model.dart';
import 'main_drawer.dart';
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Image.asset('lib/images/Logo.png', height: 35),
),
drawer: DrawerOnly(),
body: StoreConnector<AppState, _ViewModel>(
converter: (Store<AppState> store) => _ViewModel.create(store),
builder: (BuildContext context, _ViewModel viewModel) => Column(
children: <Widget>[Expanded(child: ItemListWidget(viewModel))],
),
),
);
}
}
class ItemListWidget extends StatelessWidget {
final _ViewModel model;
ItemListWidget(this.model);
#override
Widget build(BuildContext context) {
return ListView(
children: model.tournaments.map((Tournament tournament) {
return ListTile(
title: Text(tournament.tournName ?? 'Test'),
leading: IconButton(
icon: Icon(Icons.home),
onPressed: () => print('go to tourney'),
));
}).toList(),
);
}
}
class _ViewModel {
final List<Tournament> tournaments;
_ViewModel({this.tournaments});
factory _ViewModel.create(Store<AppState> store) {
print(store.state.tournaments.length);
return _ViewModel(tournaments: store.state.tournaments);
}
}
Here is the class definition of a Tournament
class Tournament {
final String tournName;
final String tournState;
final String tournCity;
final double distanceMiles;
final int startDate;
final int endDate;
final int tID;
Tournament({
#required this.tournName,
#required this.tournState,
#required this.tournCity,
#required this.distanceMiles,
#required this.startDate,
#required this.endDate,
#required this.tID,
});
Tournament copyWith({
String tournName,
String tournState,
String tournCity,
double distanceMiles,
int startDate,
int endDate,
int tID,
}) {
return Tournament(
tournName: tournName ?? this.tournName,
tournState: tournState ?? this.tournState,
tournCity: tournCity ?? this.tournCity,
distanceMiles: distanceMiles ?? this.distanceMiles,
startDate: startDate ?? this.startDate,
endDate: endDate ?? this.endDate,
tID: tID ?? this.tID,
);
}
}
This is my redux middleware handling the async task
class NearTournamentsMiddleware extends MiddlewareClass<AppState> {
#override
void call(Store<AppState> store, dynamic action, NextDispatcher next) {
if (action is NearTournamentsAction) {
checkNearTournaments(next);
}
next(action);
}
void checkNearTournaments(NextDispatcher next) async {
final tournaments = await _tournamentsInRange();
for (final tournament in tournaments) {
next(AddTournamentsAction(
tournament['TournName'],
tournament['TID'],
tournament['TournState'],
tournament['TournCity'],
tournament['Distance_Miles'],
tournament['Start_Date'],
tournament['End_Date']));
}
}
_tournamentsInRange() async {
Map currentLocation = <String, double>{};
var location = Location();
try {
currentLocation = await location.getLocation();
final response = await _checkLocalTournaments(
currentLocation["latitude"], currentLocation["longitude"]);
final decoded = jsonDecode(response.body);
return decoded;
} on PlatformException {
currentLocation = null;
}
}
Future<http.Response> _checkLocalTournaments(lat, lng) async {
var url = 'https://napi.com';
var body = json.encode({
'miles': '-1', // -1 for test api
'lat': lat,
'lng': lng
});
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
final response = await http.post(url, body: body, headers: headers);
return response;
}
}
These are my current reducers
import 'package:nasp_portal_app/model/model.dart';
import 'package:nasp_portal_app/redux/actions.dart';
AppState appStateReducer(AppState state, action) {
return AppState(tournaments: tournamentReducer(state.tournaments, action));
}
List<Tournament> tournamentReducer(List<Tournament> state, action) {
if (action is AddTournamentsAction) {
return []
..addAll(state)
..add(Tournament(
tournName: action.tournName,
tournState: action.tournState,
tournCity: action.tournCity,
distanceMiles: action.distanceMiles,
startDate: action.startDate,
endDate: action.endDate,
tID: action.tID));
}
return state;
}
How can I properly access the values in the map in my screenshot? I know I have an instanced based on the debugger but cannot get its properties.
My issue was with the redux action that I was using called AddTournamentsAction
I was not using this to refer to the class variables in its constructor like so:
class AddTournamentsAction {
final String tournName;
final String tournState;
final String tournCity;
final double distanceMiles;
final int startDate;
final int endDate;
final int tID;
AddTournamentsAction(
tournName,
tournState,
tournCity,
distanceMiles,
startDate,
endDate,
tID,
);
}
To fix this I simply had to add the this keyword:
class AddTournamentsAction {
final String tournName;
final String tournState;
final String tournCity;
final double distanceMiles;
final int startDate;
final int endDate;
final int tID;
AddTournamentsAction(
this.tournName,
this.tournState,
this.tournCity,
this.distanceMiles,
this.startDate,
this.endDate,
this.tID,
);
}