Parsing nested json list to model fails flutter - flutter

I have search screen where i can serach text it will returns data like json below,but when i try to parse data it's not working i am getting data upto this line of codevar data = menu_list[i];,but when i pass data to model,it's not quite working,any idea what went wrong
Retrieve json from api function
Future<String> GetSearchdata(String search_text) async {
ProgressDialog dialog = CustomDialogs().showLoadingProgressDialog(context);
var response = await http.post(Urls.SEARCH_ALL,
headers: {"Content-Type": "application/json", "Authorization": token},
body: json.encode({"searchText": search_text, "language": "english"}));
Map<String, dynamic> value = json.decode(response.body);
var status = value['status'];
var msg_response = value['message'];
if (response.statusCode == 200) {
dialog.dismissProgressDialog(context);
if (status == true) {
var menu_list = value['doc'];
if(menu_list.length>0)
{
for (int i = 0; i < menu_list.length; i++) {
var data = menu_list[i];
_searchResult.add(SearchModel.fromJson(data));
}
setState(() {
print("UI Updated");
});
}
else{
final snackBar = SnackBar(content: Text("No data available"));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} else {
final snackBar = SnackBar(content: Text(msg_response));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} else {
final snackBar = SnackBar(content: Text(msg_response));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
}
Model
class SearchModel {
String id = "";
String name = "";
String category_name = "";
SearchModel({
this.id,
this.name,
this.category_name,
});
SearchModel.fromJson(json)
: id = json['_id'].toString(),
name = json['registrations']['name'].toString(),
category_name =json['category']['name'].toString();
}
Json
{
"status":true,
"doc":{
"registrations":[
{
"_id":"5f44b5aafc77a977e88f558c",
"name":"test shop",
"category":[
{
"name":"/Furnitue Shop"
}
]
},
{
"_id":"5f44bd1b52977b4d1411f281",
"name":"test1",
"category":[
{
"name":"/Painting"
}
]
}
]
}
}

Try my code below :
Model
class SearchModel {
String id = "";
String name = "";
String category_name = "";
SearchModel({
this.id,
this.name,
this.category_name,
});
SearchModel.fromJson(json)
: id = json['_id'].toString(),
name = json['name'].toString(),
category_name = json['category'][0]['name'].toString();
}
Retrieve json
if (response.statusCode == 200) {
dialog.dismissProgressDialog(context);
if (status == true) {
var menu_list = value['doc']["registrations"];
if(menu_list.length>0)
{
final List<SearchModel> listFromJson = menu_list.map<SearchModel>((item) => SearchModel.fromJson(item)).toList();
setState(() {
_searchResult = listFromJson;
print("UI Updated");
});
}
else{
final snackBar = SnackBar(content: Text("No data available"));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} else {
final snackBar = SnackBar(content: Text(msg_response));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} else {
final snackBar = SnackBar(content: Text(msg_response));
_scaffoldKey.currentState.showSnackBar(snackBar);
}

Few discoveries:
1.
var menu_list = value['doc'];
This should not be
var menu_list = value['doc']['registrations'];
instead? The registrations is your list, not the doc.
2.
After you access the right element, then your model should look like this:
SearchModel.fromJson(json):
id = json['_id'].toString(),
name = json['name'].toString(),
category_name =json['category']['name'].toString();
Do note, that your category is list again (I don't know if it is intended), but if it is, then first you need to get each element from you category list and get the name of those.
Or you need something like this, if you have only 1 element there:
category_name =json['category'][0]['name'].toString();

Related

How to put code with if in a separate method?

I'm using app navigation but I'm facing a problem that I can't put the if (initialLink != null)... code in a separate method so that I can then duplicate this method in different parts of the code, can you tell me how can I put this code in a separate method?
class AppRouter {
final BuildContext context;
AppRouter(this.context);
RouteMap buildRouteMap(PendingDynamicLinkData? initialLink) {
return RouteMap(
onUnknownRoute: (route) => const Redirect('/'),
routes: {
'/': (route) {
bool loggedIn =
Provider.of<AppState>(context, listen: false).isLoggedIn;
if (initialLink != null) {
String code;
final Uri deepLink = initialLink.link;
final String deeplinkString = deepLink.toString();
code = deepLink.queryParameters['code'] ?? 'No code';
var start = deeplinkString.lastIndexOf('/') + 1;
var end = deeplinkString.indexOf('?');
var extract = deeplinkString.substring(start, end);
if (extract == 'password-reset') {
return Redirect(
'/login/forgot-password',
queryParameters: {
'isSendEmail': 'true',
'code': code,
},
);
}
}
return const MaterialPage(
child: PhoneNumberPage(),
);
},
'/map': (route) {
bool loggedIn =
Provider.of<AppState>(context, listen: false).isLoggedIn;
if (loggedIn) {
return const Redirect('/home');
}
return const MaterialPage(
child: MapPage(
isUserAuth: false,
),
);
},
code to be placed in a separate function
if (initialLink != null) {
String code;
final Uri deepLink = initialLink.link;
final String deeplinkString = deepLink.toString();
code = deepLink.queryParameters['code'] ?? 'No code';
var start = deeplinkString.lastIndexOf('/') + 1;
var end = deeplinkString.indexOf('?');
var extract = deeplinkString.substring(start, end);
if (extract == 'password-reset') {
return Redirect(
'/login/forgot-password',
queryParameters: {
'isSendEmail': 'true',
'code': code,
},
);
}
}
try this.
void commonFunction(){
if (initialLink != null) {
String code;
final Uri deepLink = initialLink.link;
final String deeplinkString = deepLink.toString();
code = deepLink.queryParameters['code'] ?? 'No code';
var start = deeplinkString.lastIndexOf('/') + 1;
var end = deeplinkString.indexOf('?');
var extract = deeplinkString.substring(start, end);
if (extract == 'password-reset') {
return Redirect(
'/login/forgot-password',
queryParameters: {
'isSendEmail': 'true',
'code': code,
},
);
}
}
}
then call commonFunction() every where you need.
You use initialLink as the judgement of if..else condition. When you extract them you need to provide that parameter. Otherwise the code cannot find initialLink.
void commonFunction(PendingDynamicLinkData? initialLink){
if (initialLink != null) {
String code;
final Uri deepLink = initialLink.link;
final String deeplinkString = deepLink.toString();
code = deepLink.queryParameters['code'] ?? 'No code';
var start = deeplinkString.lastIndexOf('/') + 1;
var end = deeplinkString.indexOf('?');
var extract = deeplinkString.substring(start, end);
if (extract == 'password-reset') {
return Redirect(
'/login/forgot-password',
queryParameters: {
'isSendEmail': 'true',
'code': code,
},
);
}
}
}

" _CastError (Null check operator used on a null value) " Flutter

When interacting with my function that initiate specs, flutter return me this error : "_CastError (Null check operator used on a null value)"
error code :
initSpecsTechs() async {
specs = await APIBike()
.getSpecsTechs(jwt: _user!.jwt, bikeId: favoriteBike!.id);
initBluetoothConnection();
initSliderAutomaticExtinctionValue();
initSliderAutomaticLockingValue();
initBackLightMode();
}
Full code of my page setting (first line contain the error code):
import 'package:myapp/api_bike.dart';
import 'package:myapp/api_user.dart';
import 'package:myapp/ux_components.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'blur_filter.dart';
class SettingsPage extends StatefulWidget {
#override
SettingsPageState createState() => SettingsPageState();
SettingsPage({required Key key}) : super(key: key);
}
class SettingsPageState extends State<SettingsPage>
with AutomaticKeepAliveClientMixin<SettingsPage> {
User? _user;
List<Bike> _bikes = [];
Bike? favoriteBike;
Specs? specs;
bool connectedByBluetooth = true;
double _currentSliderAutomaticExtinctionValue = 0;
double _currentSliderAutomaticLockingValue = 0;
bool theftAlertIsActive = true;
bool batteryAlertIsActive = true;
bool maintainAlertIsActive = true;
bool constantBackLight = true;
double spaceAfterSmallTitle = 15;
double spaceAfterWidget = 20;
//INIT FUNCTIONS
init() async {
await initUser();
await initBikes();
await initFavoriteBike();
await initSpecsTechs();
}
Future initUser() async {
final storage = new FlutterSecureStorage();
String mail = await storage.read(key: "mail") ?? "";
String password = await storage.read(key: "password") ?? "";
UserResponse userResponse = await APIUser()
.login(mail, password); //L'identifiant peut ĂȘtre le username ou le mail
User? user = userResponse.user;
if (user != null) {
setState(() {
_user = user;
});
}
return user;
}
initBikes() async {
if (_user != null) {
List<Bike> bikes = await APIBike().getAllUserBikes(jwt: _user!.jwt);
setState(() {
_bikes = bikes;
});
} else {
print("could not get the bikes call the user is null");
}
}
initFavoriteBike() async {
if (_bikes.length == 0) {
favoriteBike = null;
} else if (_bikes.length == 1) {
setState(() {
favoriteBike = _bikes.first;
});
} else {
Bike? favBike = await APIBike().getFavoriteBike(jwt: _user!.jwt);
if (favBike != null) {
setState(() {
favoriteBike = favBike;
});
} else {
print("PROBLEM : FAVORITE BIKE IS NULL");
}
}
}
initSpecsTechs() async {
specs = await APIBike()
.getSpecsTechs(jwt: _user!.jwt, bikeId: favoriteBike!.id);
initBluetoothConnection();
initSliderAutomaticExtinctionValue();
initSliderAutomaticLockingValue();
initBackLightMode();
}
initBackLightMode() {
if (specs != null) {
bool constantBackLightValue = false;
if (specs!.rearLight == "fixed") {
constantBackLightValue = true;
}
setState(() {
constantBackLight = constantBackLightValue;
});
} else {
print("Fake value used for initBackLightMode");
}
}
initTheftAlertIsActive() {
if (specs != null) {
setState(() {
theftAlertIsActive = specs!.theftAlarm;
});
} else {
print("Fake value used for initStealAlertIsActive");
}
}
initBatteryAlertIsActive() {
if (specs != null) {
setState(() {
batteryAlertIsActive = specs!.batteryAlarm;
});
} else {
print("Fake value used for initBatteryAlertIsActive");
}
}
initMaintenanceAlertIsActive() {
if (specs != null) {
setState(() {
maintainAlertIsActive = specs!.maintenanceAlarm;
});
} else {
print("Fake value used for initMaintenanceAlertIsActive");
}
}
initBluetoothConnection() {
//If this value is false then the page is all grey with nothing active
setState(() {
connectedByBluetooth = true;
});
}
initSliderAutomaticExtinctionValue() {
if (specs != null) {
double sliderValue = 0;
if (specs!.automaticSwitchOff == 0) {
sliderValue = 4;
} else if (specs!.automaticSwitchOff == 5) {
sliderValue = 0;
} else if (specs!.automaticSwitchOff == 10) {
sliderValue = 1;
} else if (specs!.automaticSwitchOff == 15) {
sliderValue = 2;
} else if (specs!.automaticSwitchOff == 20) {
sliderValue = 3;
} else {
//If there is a problem (it is not suppose to happen, we set it to never)
sliderValue = 0;
}
setState(() {
_currentSliderAutomaticExtinctionValue = sliderValue;
});
} else {
print("Fake value used for initSliderAutomaticExtinctionValue");
}
}
initSliderAutomaticLockingValue() {
if (specs != null) {
double sliderValue = 0;
if (specs!.automaticLocking == 0) {
sliderValue = 4;
} else if (specs!.automaticLocking == 1) {
sliderValue = 0;
} else if (specs!.automaticLocking == 3) {
sliderValue = 1;
} else if (specs!.automaticLocking == 5) {
sliderValue = 2;
} else if (specs!.automaticLocking == 10) {
sliderValue = 3;
} else {
//If there is a problem (it is not suppose to happen, we set it to never)
sliderValue = 0;
}
setState(() {
_currentSliderAutomaticLockingValue = sliderValue;
});
} else {
print("Fake value used for initSliderAutomaticLockingValue");
}
}
#override
void initState() {
super.initState();
init();
}
//UPDATE FUNCTIONS
updateRearLightValue(String newValue) async {
//TODO change the value on the bike by BLE
bool operationSucceed = await APIBike().updateSpecsTechs(
jwt: _user!.jwt,
bikeId: favoriteBike!.id,
specToUpdate: "rear_light",
newSpecValue: newValue);
if (operationSucceed) {
print("Rear light value updated successfully");
} else {
print("Error: rear light value didn't update correctly");
}
return operationSucceed;
}
updateAutomaticShutDownValue(double sliderValue) async {
//TODO change the value on the bike by BLE
int newValue = 0; // is also the value for never
if (sliderValue == 0) {
newValue = 5;
} else if (sliderValue == 1) {
newValue = 10;
} else if (sliderValue == 2) {
newValue = 15;
} else if (sliderValue == 3) {
newValue = 20;
} //else the new value is 0 which is never
bool operationSucceed = await APIBike().updateSpecsTechs(
jwt: _user!.jwt,
bikeId: favoriteBike!.id,
specToUpdate: "automatic_switch_off",
newSpecValue: newValue);
if (operationSucceed) {
print("Automatic switch off value updated successfully");
} else {
print("Error: Automatic switch off value didn't update correctly");
}
return operationSucceed;
}
updateAutomaticLockingValue(double sliderValue) async {
//TODO change the value on the bike by BLE
int newValue = 0; // is also the value for never
if (sliderValue == 0) {
newValue = 1;
} else if (sliderValue == 1) {
newValue = 3;
} else if (sliderValue == 2) {
newValue = 5;
} else if (sliderValue == 3) {
newValue = 10;
} //else the new value is 0 which is never
bool operationSucceed = await APIBike().updateSpecsTechs(
jwt: _user!.jwt,
bikeId: favoriteBike!.id,
specToUpdate: "automatic_locking",
newSpecValue: newValue);
if (operationSucceed) {
print("Automatic locking value updated successfully");
} else {
print("Error: Automatic locking value didn't update correctly");
}
return operationSucceed;
}
updateTheftAlertIsActive(bool newValue) async {
bool operationSucceed = await APIBike().updateSpecsTechs(
jwt: _user!.jwt,
bikeId: favoriteBike!.id,
specToUpdate: "theft_alarm",
newSpecValue: newValue);
if (operationSucceed) {
print("Theft alert value updated successfully");
} else {
print("Error: theft alert value didn't update correctly");
}
return operationSucceed;
}
updateBatteryAlertIsActive(bool newValue) async {
bool operationSucceed = await APIBike().updateSpecsTechs(
jwt: _user!.jwt,
bikeId: favoriteBike!.id,
specToUpdate: "battery_alarm",
newSpecValue: newValue);
if (operationSucceed) {
print("Battery alert value updated successfully");
} else {
print("Error: battery alert value didn't update correctly");
}
return operationSucceed;
}
updateMaintenanceAlertIsActive(bool newValue) async {
bool operationSucceed = await APIBike().updateSpecsTechs(
jwt: _user!.jwt,
bikeId: favoriteBike!.id,
specToUpdate: "maintenance_alarm",
newSpecValue: newValue);
if (operationSucceed) {
print("Maintenance alert value updated successfully");
} else {
print("Error: maintenance alert value didn't update correctly");
}
return operationSucceed;
}
/.../
And finally my api for the user :
import 'dart:collection';
import 'package:myapp/api_bike.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class ResponseWithError {
final bool result;
final String error;
ResponseWithError(this.result, this.error);
}
class APIUser {
//For dev
final String serverAddress =
"https://myadress.com/";
//TODO For production:
//final String serverAddress = "https://prodadress.com";
Future<ResponseWithError> createUser(
String firstname, String lastname, String email, String password) async {
var body =
"""{"username": "$firstname $lastname", "firstname": "$firstname", "lastname": "$lastname", "email": "$email", "password": "$password"}""";
var client = new http.Client();
var response = await client.post(
Uri.parse("$serverAddress/auth/local/register"),
body: body,
headers: {"Content-Type": 'application/json'});
if (response.statusCode == 200) {
print("USER CREATED");
print(response.body);
return ResponseWithError(true, "none");
} else {
print("Error " + response.statusCode.toString());
print("Response Body");
print(response.body);
var responseBody = jsonDecode(response.body);
if (responseBody["message"][0]["messages"][0]["id"] != null) {
String errorMessageId = responseBody["message"][0]["messages"][0]["id"];
if (errorMessageId == "Auth.form.error.email.format") {
return ResponseWithError(false, "email format");
}
}
return ResponseWithError(false, "not known");
}
}
Future<UserResponse> login(String identifier, String password) async {
var body = """{"identifier": "$identifier", "password": "$password"}""";
var client = new http.Client();
var response = await client.post(Uri.parse("$serverAddress/auth/local"),
body: body, headers: {"Content-Type": 'application/json'});
if (response.statusCode == 200) {
//print("USER LOGGED IN");
final parsed = jsonDecode(response.body);
User user = User.fromJson(parsed);
UserResponse userResponse = UserResponse(user, true);
return userResponse;
} else {
//print("Error " + response.statusCode.toString());
//print("Response Body");
//print(response.body);
var responseBody = jsonDecode(response.body);
if (responseBody["message"][0]["messages"][0]["id"] != null) {
String errorMessageId = responseBody["message"][0]["messages"][0]["id"];
if (errorMessageId == "Auth.form.error.confirmed") {
print("User not confirmed");
UserResponse userResponse = UserResponse(null, false);
return userResponse;
} else /*if(errorMessageId == "Auth.form.error.invalid")*/ {
print("email or password incorrect");
UserResponse userResponse = UserResponse(null, true);
return userResponse;
}
}
//Should not happen, but just in case
UserResponse userResponse = UserResponse(null, true);
return userResponse;
}
}
Future<bool> updateToken(String jwt, String notificationId) async {
var body = """{"notification_id": "$notificationId"}""";
var client = new http.Client();
var response = await client.put(Uri.parse("$serverAddress/users/token"),
body: body,
headers: {
"Content-Type": 'application/json',
'Authorization': 'Bearer $jwt'
});
if (response.statusCode == 200) {
print("NOTIFICATION TOKEN UPDATED");
return true;
} else {
print("Error " + response.statusCode.toString());
print("Response Body");
print(response.body);
return false;
}
}
Future<bool> updateEmail(String jwt, String newEmail) async {
var confirmed = false;
var body = """{"email": "$newEmail", "confirmed": "$confirmed"}""";
var client = new http.Client();
var response = await client.put(Uri.parse("$serverAddress/users/me"),
body: body,
headers: {
"Content-Type": 'application/json',
'Authorization': 'Bearer $jwt'
});
if (response.statusCode == 200) {
print("EMAIL UPDATED");
return true;
} else {
print("Error " + response.statusCode.toString());
print("Response Body");
print(response.body);
return false;
}
}
Future<bool> updateNames(
String jwt, String newFirstname, String newLastName) async {
var body =
"""{"username": "$newFirstname $newLastName", "firstname": "$newFirstname", "lastname": "$newLastName"}""";
var client = new http.Client();
var response = await client.put(Uri.parse("$serverAddress/users/me"),
body: body,
headers: {
"Content-Type": 'application/json',
'Authorization': 'Bearer $jwt'
});
if (response.statusCode == 200) {
print("NAMES UPDATED");
return true;
} else {
print("Error " + response.statusCode.toString());
print("Response Body");
print(response.body);
return false;
}
}
Future<bool> updatePassword(String jwt, String newPassword) async {
var body = """{"password": "$newPassword"}""";
var client = new http.Client();
var response = await client.put(Uri.parse("$serverAddress/users/me"),
body: body,
headers: {
"Content-Type": 'application/json',
'Authorization': 'Bearer $jwt'
});
if (response.statusCode == 200) {
print("PASSWORD UPDATED");
return true;
} else {
print("Error " + response.statusCode.toString());
print("Response Body");
print(response.body);
return false;
}
}
Future<bool> sendConfirmationCode(String email) async {
var body = """{"email": "$email"}""";
var client = new http.Client();
var response = await client.post(
Uri.parse("$serverAddress/auth/send-email-confirmation"),
body: body,
headers: {"Content-Type": 'application/json'});
if (response.statusCode == 200) {
print("EMAIL SENT to $email");
return true;
} else {
print("Error " + response.statusCode.toString());
print("Response Body");
print(response.body);
return false;
}
}
Future<bool> verifyEmail(String email, String code) async {
var body = """{"email": "$email", "confirmation": "$code"}""";
var client = new http.Client();
var response = await client.put(
Uri.parse("$serverAddress/auth/email-confirmation"),
body: body,
headers: {"Content-Type": 'application/json'});
if (response.statusCode == 200) {
print("EMAIL VERIFIED");
return true;
} else {
print("Error " + response.statusCode.toString());
print("Response Body");
print(response.body);
return false;
}
}
Future<bool> passwordForgotten({required String email}) async {
var body = """{"email": "$email"}""";
var client = new http.Client();
var response = await client.post(
Uri.parse("$serverAddress/auth/forgot-password"),
body: body,
headers: {"Content-Type": 'application/json'});
if (response.statusCode == 200) {
return true;
} else {
print("Error passwordForgotten :" + response.statusCode.toString());
print("Response Body");
print(response.body);
return false;
}
}
}
class UserResponse {
User? user;
bool userConfirmed;
UserResponse(this.user, this.userConfirmed);
}
class User {
final int id;
final String jwt;
final String username;
final String firstname;
final String lastname;
final String email;
final String provider;
final bool confirmed;
final bool? blocked;
final String? notificationId;
final String createdAt;
final String updatedAt;
final List<int>?
bikesId; //Here we just save the ids of the bikes linked to the user
final Subscription? subscription;
final Role role;
User({
required this.id,
required this.jwt,
required this.username,
required this.firstname,
required this.lastname,
required this.email,
required this.provider,
required this.confirmed,
required this.blocked,
required this.notificationId,
required this.createdAt,
required this.updatedAt,
required this.bikesId,
required this.subscription,
required this.role,
});
factory User.fromJson(Map<String, dynamic> json) {
if (json['user']['subscription'] != null) {
return User(
id: json['user']['id'] as int,
jwt: json['jwt'] as String,
username: json['user']['username'] as String,
firstname: json['user']['firstname'] as String,
lastname: json['user']['lastname'] as String,
email: json['user']['email'] as String,
provider: json['user']['provider'] as String,
confirmed: json['user']['confirmed'] as bool,
blocked: json['user']['blocked'] as bool?,
notificationId: json['user']['notification_id'] as String?,
createdAt: json['user']['created_at'] as String,
updatedAt: json['user']['updated_at'] as String,
bikesId: createBikesIdList(json['user']['bikes_id']),
subscription: Subscription(
id: json['user']['subscription']['id'],
name: json['user']['subscription']['name'],
createdAt: json['user']['subscription']['created_at'],
updatedAt: json['user']['subscription']['updated_at']),
role: Role(
id: json['user']['role']['id'],
name: json['user']['role']['name'],
description: json['user']['role']['description'],
type: json['user']['role']['type'],
));
} else {
return User(
id: json['user']['id'] as int,
jwt: json['jwt'] as String,
username: json['user']['username'] as String,
firstname: json['user']['firstname'] as String,
lastname: json['user']['lastname'] as String,
email: json['user']['email'] as String,
provider: json['user']['provider'] as String,
confirmed: json['user']['confirmed'] as bool,
blocked: json['user']['blocked'] as bool?,
notificationId: json['user']['notification_id'] as String?,
createdAt: json['user']['created_at'] as String,
updatedAt: json['user']['updated_at'] as String,
bikesId: createBikesIdList(json['user']['bikes_id']),
subscription: null,
role: Role(
id: json['user']['role']['id'],
name: json['user']['role']['name'],
description: json['user']['role']['description'],
type: json['user']['role']['type'],
));
}
}
describe() {
print("id : $id\njwt : $jwt");
}
}
class Role {
final int id;
final String name;
final String description;
final String type;
Role({
required this.id,
required this.name,
required this.description,
required this.type,
});
}
class Subscription {
final int id;
final String name;
final String createdAt;
final String updatedAt;
Subscription(
{required this.id,
required this.name,
required this.createdAt,
required this.updatedAt});
}
Can you try like this? I think user or favoriteBike is null. You need to null check.
initSpecsTechs() async {
if(_user != null && favoriteBike != null){
specs = await APIBike()
.getSpecsTechs(jwt: _user!.jwt, bikeId: favoriteBike!.id);
initBluetoothConnection();
initSliderAutomaticExtinctionValue();
initSliderAutomaticLockingValue();
initBackLightMode();
}
}
initSpecsTechs() async {
specs = await APIBike()
.getSpecsTechs(jwt: _user!.jwt, bikeId: favoriteBike!.id);
initBluetoothConnection();
initSliderAutomaticExtinctionValue();
initSliderAutomaticLockingValue();
initBackLightMode();
}
The "!" operator causes the exception instead use "?" like this
specs = await APIBike()
.getSpecsTechs(jwt: _user?.jwt??'', bikeId: favoriteBike?.id??'');

I am having a problem to fetch and display a single item in Flutter from API

I have an endpoint that returns data in the following JSON format.
{
"data": [
{
"balance": "40.000000"
}
]
}
I want to display the above balance into a wallet UI. I am having difficulty to display a single element that is not using controller formfield.
Below is additional code:
wallet_service.dart
Future<ApiResponse> getWalletBalance() async {
ApiResponse apiResponse = ApiResponse();
try {
String token = await getToken();
final response = await http.get(Uri.parse(wallet),
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer $token'
});
switch(response.statusCode){
case 200:
apiResponse.data = Wallet.fromJson(jsonDecode(response.body));
break;
case 401:
apiResponse.error = unauthorized;
break;
default:
apiResponse.error = somethingWentWrong;
break;
}
}
catch (e){
apiResponse.error = serverError;
}
return apiResponse;
}
walletui.dart
class _DashboardState extends State<Dashboard> {
Wallet? wallet;
bool loading = true;
GlobalKey<FormState> formKey = GlobalKey<FormState>();
//TextEditingController txtBalanceController = TextEditingController();
//int mybalance=0;
// get user detail
void getUserWallet() async {
ApiResponse response = await getWalletBalance();
if(response.error == null) {
setState(() {
wallet = response.data as Wallet;
//log('data: $wallet');
loading = false;
//txtBalanceController.text = wallet?.balance?? '';
});
}
else if(response.error == unauthorized){
logout().then((value) => {
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context)=>Login()), (route) => false)
});
}
else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('${response.error}')
));
}
}
#override
void initState() {
getUserWallet();
super.initState();
}
}
Wallet Model Class
class Wallet {
int? id;
String? balance;
Wallet({
this.id,
this.balance,
});
factory Wallet.fromJson(Map<String, dynamic> json){
return Wallet(
id: json['id'],
balance: json['balance'],
);
}
}
My goal is to store the balance in a variable wallet that I can execute in the UI and display that value.
Please follow this link call for api:https://github.com/JayswalViraj/Flutter-Login-With-Rest-API
Please you understand after implemente.

How to solve this List<dynamic> type error in Flutter/Dart

I am very new to flutter and dart. Trying to return a list from this future that pulls data from an api but I keep getting this error. Someone here helped me solve a similar error by casting to a list because I was calling map function on an array that returns an iterable but in this case here I'm not sure what needs to be done.
type List<dynamic> is not a subtype of type FutrueOr<ListCity>>
Data is received like below:
{
"data": {
"127287": {
"Feature_int_id": "127287",
"Admin1_str_code": "US06",
"Country_str_code": "US",
"Feature_str_name": "Acampo",
"Feature_dec_lat": "38.194",
"Feature_dec_lon": "-121.25"
},
"116496": {
"Feature_int_id": "116496",
"Admin1_str_code": "US06",
"Country_str_code": "US",
"Feature_str_name": "Acton",
"Feature_dec_lat": "34.49",
"Feature_dec_lon": "-118.22"
},
"124284": {
"Feature_int_id": "124284",
"Admin1_str_code": "US06",
"Country_str_code": "US",
"Feature_str_name": "Adelanto",
"Feature_dec_lat": "34.665",
"Feature_dec_lon": "-117.512"
},
}
Below is the code for future:
Future<List<City>> fetchCitiesByProvince(provinceCode) async {
final response = await http.get(Uri.https('localhost/msd', 'api/cities/' + provinceCode));
final responseJson = json.decode(response.body);
final dataMap = responseJson['data'];
if (response.statusCode == 200) {
List citiesList = [];
for (var city in dataMap.keys) {
if (dataMap[city]['Admin1_str_code'] == provinceCode) {
citiesList.add(
{
'cityCode': dataMap[city]['Feature_int_id'],
'cityName': dataMap[city]['Feature_str_name']
}
);
}
}
return citiesList;
} else {
throw Exception('Failed to load cities');
}
}
City Class:
class City {
final String cityCode;
final String cityName;
City({#required this.cityCode, #required this.cityName});
factory City.fromJson(Map<String, dynamic> json) {
return City(
cityCode: json['Feature_int_id'],
cityName: json['Feature_str_name']
);
}
}
You need to return List<City> in your method. So, change the following code:
List citiesList = [];
to
List<City> citiesList = [];
--- UPDATE ---
You need to user your City constructor or factory to generate the item from json like this:
City.fromJson(dataMap[city]);
// Or
City(cityCode: dataMap[city]['Feature_int_id'],
cityName: dataMap[city]['Feature_str_name']
);
Here the updated sample code:
Future<List<City>> fetchCitiesByProvince(provinceCode) async {
final response = await http.get(Uri.https('localhost/msd', 'api/cities/' + provinceCode));
final responseJson = json.decode(response.body);
final dataMap = responseJson['data'];
List<City> citiesList = [];
if (response.statusCode == 200) {
for (var city in dataMap.keys) {
if (dataMap[city]['Admin1_str_code'] == provinceCode) {
citiesList.add(City.fromJson(dataMap[city]));
}
}
} else {
throw Exception('Failed to load cities');
// either throwing an error or return empty list.
}
return citiesList;
}

Flutter: value of type 'Future<List<UserVideo>>' can't be assigned to a variable of type 'List<UserVideo>'

I am trying to use one List (custom type) but getting error.
When i try to use the getData() function. Like below.
List<UserVideo> videoDataList = [];
videoDataList = UserVideo.getData();
This is initState method.
#override
void initState() {
videoDataList = await UserVideo.getData();
WidgetsBinding.instance.addObserver(this);
_videoListController.init(
_pageController,
videoDataList,
);
super.initState();
}
I am getting the error.
A value of type 'Future<List<UserVideo>>' can't be assigned to a variable of type 'List<UserVideo>'.
Try changing the type of the variable, or casting the right-hand type to 'List<UserVideo>'.
Here is the code for function.
class UserVideo {
final String url;
final String image;
final String desc;
UserVideo({
this.url: mockVideo,
this.image: mockImage,
this.desc,
});
Future <List<UserVideo>> getData() async {
List<UserVideo> list = [];
try {
var deviceid = '123';
var dtgUid = '100';
var nodata;
var bodyss = {
"uid": dtgUid,
"deviceid": deviceid,
};
var url = 'http://192.168.100.4:8080/videos/get-data.php';
// Starting Web API Call.
var response = await http
.post(url, body: json.encode(bodyss))
.timeout(Duration(seconds: 5), onTimeout: () {
return null;
});
if (response.statusCode == 200) {
final data = StreamingFromJson(response.body);
if (data.count == null) {
count = 0;
} else {
count = data.count;
}
if (data.content.length > 0 && data.content[0].name != 'Empty') {
for (var i in data.content) {
list.add(UserVideo(image: i.thumbnail, url: i.video, desc: i.title));
}
} else {
nodata = 'No Record Found';
}
print(list.length);
}
} catch (e) {
print("Exception Caught: $e");
}
return list;
}
Edit:
Just showing the hardcoded value which is working fine.
static List<UserVideo> fetchVideo() {
List<UserVideo> list = [];
list.add(UserVideo(image: '', url: mockVideo, desc: 'Test1'));
list.add(UserVideo(image: '', url: mV2, desc: 'MV_TEST_2'));
list.add(UserVideo(image: '', url: mV3, desc: 'MV_TEST_3'));
list.add(UserVideo(image: '', url: mV4, desc: 'MV_TEST_4'));
return list;
}
I can use it like this and no error.
videoDataList = UserVideo.fetchVideo();
Your method getData() returns a Future:
Future<List<UserVideo>> getData() async {
List<UserVideo> list = [];
try {
var deviceid = '123';
var dtgUid = '100';
var nodata;
var bodyss = {
"uid": dtgUid,
"deviceid": deviceid,
};
You have to use async/await to call the method getData():
List<UserVideo> videoDataList = [];
videoDataList = await UserVideo.getData();
or use then():
List<UserVideo> videoDataList = [];
UserVideo.getData().then((list){
videoDataList = list;
});
Note: To use await you need to declare a method async