Cannot access map object with []. operator [] is not defined - flutter

I am working on a mobile application using Flutter 1.7.8.
I collected data from the server in a form of a nested json object, e.g.
class Obj {
final String obj_to_access;
const Obj({this.obj_to_access});
factory Obj.fromJson(Map<String, dynamic> json) {
return Obj(
obj_to_access: json['item']
);
}
some_obj =
{
"id": some_id,
"nested_obj": Obj.fromJson(json["obj_to_access"])
}
However, I can't seem to access the nested Obj with '[]' and it always give me this error: The operator '[]' isn't defined for the class 'Obj'. Try defining the operator.
I saw that I should try defining the '[]' but I am not sure how. Please help thanks

The reason for the error is that you're passing a dynamic value to Obj.fromJson() instead of a Map - which it expects. To solve this issue, you can add cast as <Map<String, dynamic>> to the value to let the compiler know that it's a Map.

Related

In Flutter, an object's fromJson method generated by freezed occured type cast error, DateTime -> String

I have used freezed library to manage my Remote DTO classes and Ui Models.
In this question case, my Object LifeDiagnosisResult DTO and Ui Model only have one difference - createdAt field.
When I put data, I used SharedPreference (because backend is not yet built) and put my List value by jsonEncode function.
When I get a response from SharedPreference (because backend is not yet built) , I used jsonDecode to get Map Object.
To achieve my final wish, List Object, I added createdAt field like this.
void _handleListResponseSuccess(List<String> response) {
List<LifeDiagnosisResultUiModel>? uiModelList = response.map((e) {
Map<String, dynamic> map = jsonDecode(e) as Map<String, dynamic>;
map['createdAt'] = DateTime.now();
return LifeDiagnosisResultUiModel.fromJson(map);
}).toList();
if (uiModelList.isNotEmpty) {
setLifeDiagnosisResultUiModel(uiModelList[uiModelList.length - 1]);
}
_rxList(uiModelList);
}
But, when I ran this code, type casting error was caused.
The error message is this.
error type 'DateTime' is not a subtype of type 'String' in type cast
And this is my Ui Model's createdAt field.
I think Map's createdAt could not find correct field in Ui Model.
But I have no idea why...
Could you tell me what is wrong?
I found the answer...
it is not a real answer of my question, but it can explain why this issue happen.
In dart, Map's DateTime cannot be converted to Object's DateTime.
I dont know a detail process, but in type casting, Map's DateTime is converted to String type.
I don't know if I get it right, but if you want to test your fromJson method you could do it like this:
Map<String,dynamic> response={'att1':1234,'att2':'oneTwoThree','createdAt':DateTime(2022,08,22)};
return LifeDiagnosisResultUiModel.fromJson(response);

NoSuchMethodError: Class 'List<dynamic>' has no instance method 'cast' with matching arguments

I am trying to fetch Articles from my API servers,but i get NoSuchMethodError: Class 'List<dynamic>' has no instance method 'cast' with matching arguments error. Does anybody know how can i solve it?
List<Article> posts;
final response = await http.get(Uri.parse("$SERVER_IP/api/articles/?format=json"),
headers: <String, String>{"Authorization" : "Token ${globaltoken}"},);
final parsed = jsonDecode(utf8.decode(response.bodyBytes)).cast<String,dynamic>();
posts = parsed.map<Article>((json) => Article.fromJSON(json)).toList();
return posts;
You should not use cast() in the first place, because a nearby operation (in this case the parsed.map) already uses cast() for you and thus casts your desired type (Article). Omitting cast<String,dynamic>() should solve your error.
Please also refer to the dart documentation:
https://dart.dev/guides/language/effective-dart/usage#dont-use-cast-when-a-nearby-operation-will-do
https://dart.dev/guides/language/effective-dart/usage#avoid-using-cast

Migrating from Provider to Riverpod

I am stuck using Provider and came across Riverpod which is just the next gen of Provider. I am trying to create a StreamProvider using Riverpod but I am getting an error.
Here is the code for creating the StreamProvider:
final trxnStreamProvider = StreamProvider.autoDispose<List<Trxns>>((ref) {
final stream = firestoreService.getAgencyTrxns();
return stream.map((snapshot) => snapshot.docs.map((doc) => Trxns.fromFirestore(doc.data)).toList());
});
The error I get marks the code "doc.data". Here is the error text:
The argument type 'Object? Function()' can't be assigned to the parameter type 'Map<String, dynamic>'.
Here is the code for "Trxns.fromFirestore(doc.data)":
Trxns.fromFirestore(Map<String, dynamic> firestore)
: clientFName = firestore['clientFName'],
clientLName = firestore['clientLName'];
I'm still new to this and am having a hard time understanding the error message. Is it saying that "doc.data" is not the right type? If so, how do I fix this? If not, what is wrong and how do I fix it?
Map<String, dynamic> data() => dartify(jsObject.data());
data is a method so you need to call it:
doc.data()
doc.data mean you want to pass a function

Flutter/Dart API Call Throws Error (sometimes)

APIs:
https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY
https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY
API Call Method:
import 'package:http/http.dart';
import '../Models/fetched_data.dart';
Future<FetchedData?> fetchIndexDetails(String index) async {
final String url =
'https://www.nseindia.com/api/option-chain-indices?symbol=$index';
try {
final response = await get(
Uri.parse(url),
);
final FetchedData? fetchedData = fetchedDataFromJson(response.body);
return fetchedData;
} catch (e) {
print('$index Error: $e');
}
return null;
}
The json file is same for both the APIs, hence the model class too.
However, the second API call works smoothly but the first API call throws an error saying:
type 'double' is not a subtype of type 'int?'
Can anybody help me decode the problem here? Much tia :)
This is a JSON parsing issue for unmatched type parsing of the API and the your Dart Model ..
How to diagnose it?
You can always catch those errors while the development by enabling the dart debugger for uncaught exceptions, which gives you exactly the broken casting
type 'double' is not a subtype of type 'int?'
The API has returned a double value where an int is expected.
In your model or where appropriate replace the expected type to use num which int and double are both subtypes of
Check your model class where you have defined different variables and match with data type you are getting in response from the json.
There must be a variable you have defined in model class as int? but u r getting double as a response so u got to convert the data type .
Seems like you are trying to map a double to int?, the response had a double and you are assigning it to int?, add a breakpoint when mapping the response to see the corresponding field. You can try casting it to int or just changing the type all together.

A value of type 'List<Customer>' can't be assigned to a variable of type 'Future<List<Customer>>'

How to convert 'List' to 'Future<List>'. I need get two type ('List' & 'Future<List>' ) in different places
My api response
var data = jsonDecode(r.body);
custList.add(new Customer(
data[i]['CustomerID'],
'${data[i]['ProfileImageUrl']}' + '${data[i]['ProfileImage']}',
'${data[i]['CompanyName']}',
data[i]['Email'],
data[i]['RegisterNumber'],
data[i]['PhoneNumber'],
data[i]['BillingStreet'],
data[i]['BillingCity'],
data[i]['BillingZip'],
data[i]['MasterCountryName'],
data[i]['MasterStateName'],
data[i]['Type'],
new customeraddress(data[i]['BillingStreet'],
data[i]['BillingCity'], data[i]['BillingZip']),
status,
data[i]['CustomerTaxExemptType'],
data[i]['MasterCountryID'],
data[i]['MasterStateID'],
));
How to convert 'List' to 'Future<List>'.
If you are not entirely sure if you get a T or a Future<T>, you can use the FutureOr<T> (documentation) class.
To create a Future<T> from a value to satisfy some compiler syntax, you can use the named constructor Future.value (documentation).
For more information on Futures: What is a Future and how do I use it?