the method 'map' was called on null. flutter [closed] - flutter

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to get user from Json,but somehow i get en error that says
the method 'map' was called on null. flutter
I don't know why,here are my codes for my models:
class User {
final String id;
final String email;
final String username;
List<FollowUserModel> following = [];
List<FollowUserModel> followers = [];
User({this.id,this.email,this.followers,this.following, this.username});
factory User.fromJSON(Map<String, dynamic> jsonMap) {
return User(
id: jsonMap['id'] as String,
email: jsonMap['email'] as String,
username: jsonMap['username'] as String,
following: jsonMap["following_set"] != null ? List<FollowUserModel>.from( jsonMap["followiing_set"].map((x) => FollowUserModel.fromJSON(x))) :[],
followers: jsonMap["followers_set"] != null ? List<FollowUserModel>.from( jsonMap["followers_set"].map((x) => FollowUserModel.fromJSON(x))) :[],
);
}
}
class FollowUserModel {
final String id;
final User author;
final User profile;
FollowUserModel({this.id,this.author,this.profile});
factory FollowUserModel.fromJSON(Map<String, dynamic> jsonMap) {
return FollowUserModel(
id: jsonMap['id'] as String,
author: jsonMap['author'] as User,
profile: jsonMap['profile'] as User,
);
}
}
And here is my full error code from my exception:
I declared the arrays as [] before as i expect some null returns but still,i get the error. Anybody knows the reason?
Update
I know i made typo,but still the error exists.

You made typos, instead of 'following_set' and 'followers_set' you have written 'followiing_set' and 'followrse_set':
....
following: jsonMap["following_set"] != null ? List<FollowUserModel>.from( jsonMap["followiing_set"].map((x) => FollowUserModel.fromJSON(x))) :[],
followers: jsonMap["followers_set"] != null ? List<FollowUserModel>.from( jsonMap["followrse_set"].map((x) => FollowUserModel.fromJSON(x))) :[],
....

Related

An exception "flutter: type 'Null' is not a subtype of type 'String'" is thrown when formatting json data in flutter

I want to fetch and format json data from this as a trial in flutter. However, during the formatting process, an exception occurs: type 'Null' is not a subtype of type 'String'.
And these are my code:
user_model.dart
class User {
int id;
String email;
String firstName;
String lastName;
String avator;
User({
required this.id,
required this.email,
required this.firstName,
required this.lastName,
required this.avator
});
factory User.fromJson(Map<String, dynamic> json) => User(
id : json['id'],
email : json['email'],
firstName : json['first_name'],
lastName : json['last_name'],
avator : json['avator']
);
}
user_api.dart
...
class UserApi {
Future<List<User>?> getUsers() async {
final url = Uri.parse('https://reqres.in/api/users?page=2');
try {
final res = await http.get(url);
if (res.statusCode == 200) {
final Map<String, dynamic> body = jsonDecode(res.body);
final List<User> users = body['data'].map((dynamic userData) => {
print('userData : $userData');
User.fromJson(userData) // There seems to be an error here.
}).toList();
return users;
} else {
return null;
}
} catch (e) {
print(e.toString());
}
return null;
}
}
And userData seems like this in my console:
flutter: userData : {id: 7, email: michael.lawson#reqres.in, first_name: Michael, last_name: Lawson, avatar: https://reqres.in/img/faces/7-image.jpg}
I don't think userData is kind of Null, but why do I get the exception?
You need to use json['avatar'] instead of json['avator']
factory User.fromJson(Map<String, dynamic> json) => User(
id : json['id'],
email : json['email'],
firstName : json['first_name'],
lastName : json['last_name'],
avator : json['avatar'] //here `a` instead of `o`
);
I just checked the link you have mentioned for the json you are using. There is a typo at your end. In the json, avatar is the correct field spelling. You have mentioned avator in your class's factory constructor.
So, avator is Null and thus, String avator is assigned to a Null value.
FYI: The error type 'Null' is not a subtype of type 'String' means that you are trying to assign a Null value to a String type variable.
its a typo in the fromJson method : as mentioned by yeasin-sheikh (You need to use json['avatar'] instead of json['avator']),
Yeasin-sheikh's answer
there are some json parsing websites, using that we can easily generate model class and other methods related to it.
eg : app.quicktype.io
just input the json response and generate the model class in required language.

Flutter firestore database returns null [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I have following code:
I use cloud firestore as database
UserModel:
class DbUser {
String id;
final String authUserID;
final String userName;
final List<String>? itemsForSale;
final List<String>? itemFavourites;
final List<String>? bids;
DbUser(
{this.id = '',
required this.authUserID,
required this.userName,
this.itemsForSale,
this.itemFavourites,
this.bids});
Map<String, dynamic> toJson() => {
'id': id,
'authUserID': authUserID,
'userName': userName,
'itemsForSale': itemsForSale,
'itemFavourites': itemFavourites,
'bids': bids,
};
static DbUser fromJson(Map<String, dynamic> json) => DbUser(
id: json['id'],
authUserID: json['authUserID'],
userName: json['userName'],
itemsForSale: json['itemsForSale'] is Iterable
? List.from(json['itemsForSale'])
: null,
itemFavourites: json['itemFavourites'] is Iterable
? List.from(json['itemFavourites'])
: null,
bids: json['bids'] is Iterable ? List.from(json['bids']) : null,
);
}
Repository class
final _firestoreDB = FirebaseFirestore.instance;
Future<DbUser?> getDBUserByDBUserId({required String dbUserID}) async {
final docUser = _firestoreDB.collection('users').doc(dbUserID);
final snapshot = await docUser.get();
if (snapshot.exists) {
return DbUser.fromJson(snapshot.data()!);
}
return null;
}
snapshot.exists returns false.
I do not understand why?
my snapshot returns null but I do not see why it does that, could somebody please help me?
Thank you
Space
found my problem, there was a space before my Id that had been retreived, I must have accedentally put it there when creating the database...
Looking at the screenshot of the document you shared, the document ID in the second column is different from the value of authUserID in the third column. So it seems like you added the document by calling add, which means that Firestore generates a unique ID for you.
You then create a reference to the document with this code:
_firestoreDB.collection('users').doc(dbUserID)
But here you are specifying dbUserID as the document ID, which doesn't match what you did when you created the document. Firestore now looks for a document with an ID that is the same as the user ID, which doesn't exist and thus gives you a snapshot where exists is false.
If you want to find the document for the user in your current structure, you can use a query to do so:
Future<DbUser?> getDBUserByDBUserId({required String dbUserID}) async {
final query = _firestoreDB.collection('users').where('authUserID', isEqualTo: dbUserID)
final snapshot = await query.get();
if (snapshot.size > 0) {
return DbUser.fromJson(snapshot.docs[0]!.data()!);
}
return null;
}
But a better solution might be to actually store the user document under its user ID. You can specify the document ID as shown in the documentation on setting a document. So here you'd call .document('theuserid').set(...) instead of add(...).

How to fix Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'String' in flutter?

Right now I'm working on the create profile page section. Which before coming to this page will verify the identity by using the otp code and will receive the token of the user as well in order to check whether this token has already applied to the system. If you haven't applied yet, you will come to the profile creation page. But if you have already applied, you can go straight to the main page.
But now I'm stuck with the problem that When pressing the confirm button on the profile creation page, this error occurs. where i want to fetch data from local storage which i have created sharedpreference to store and retrieve data already After that I created a model in response to the profiling, created the dio package used to build the network api in flutter, but I still can't find where it went wrong.
it's dio_client.dart
Future<ProfileUserResponseModel> createProfile({
required String fullName,
required String idLine,
required String birthDate,
required String? gender,
}) async {
final request = ProfileUserRequestModel(
fullName: fullName, idLine: idLine, birthDate: birthDate, gender: gender);
final response =
await dioToken().post(ApiConstants.createProfile, data: request.toJson());
try {
if (response.statusCode == 201) {
return ProfileUserResponseModel.fromJson(response.data);
} else {
throw Exception('Failed to create your profile');
}
} on DioError catch (e) {
throw Exception(e);
}
}
it's profile_user_request_model.dart
class ProfileUserRequestModel {
ProfileUserRequestModel(
{required this.fullName,
required this.idLine,
required this.birthDate,
required this.gender});
String fullName;
String idLine;
String birthDate;
String? gender;
factory ProfileUserRequestModel.fromJson(Map<String, dynamic> json) {
return ProfileUserRequestModel(
fullName: json["full_name"],
idLine: json["id_line"],
birthDate: json["birth_date"],
gender: json["gender"],
);
}
Map<String, dynamic> toJson() => {
"full_name": fullName,
"id_line": idLine,
"birth_date": birthDate,
"gender": gender,
};
}
I think it may be caused by mistake getting gender variable from radio button. But I have already defined it as a string. But it can't be used. If anyone knows a way to fix the problem. Feel free to reply in the comments. Thank you very much.

how to make a list in null safe version in flutter? [duplicate]

This question already has answers here:
The default 'List' constructor isn't available when null safety is enabled. Try using a list literal, 'List.filled' or 'List.generate'
(4 answers)
Closed 1 year ago.
I'm creating a modal class for calling API and I got an error
The default 'List' constructor isn't available when null safety is enabled.
Try using a list literal, 'List.filled' or 'List.generate'.
I studied some answers on StackOverflow but I don't understand the answer.
class Autogenerated {
bool? status;
String? message;
List<Data>? data;
Autogenerated({required this.status,required this.message,required this.data});
Autogenerated.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
if (json['data'] != null) {
data = new List<Data> (); ///error List<Data>()
json['data'].forEach((v) {
data?.add(new Data.fromJson(v));
});
}
}
///other code
}
just change it this way
class Autogenerated {
bool? status;
String? message;
List<Data>? data;
Autogenerated({required this.status,required this.message,required this.data});
Autogenerated.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
if (json['data'] != null) {
data = [];
json['data'].forEach((v) {
data?.add(new Data.fromJson(v));
});
}
}
///other code
}

Flutter Bloc : Fetch Firestore Data Into Model

I'm trying to fetch data from Firestore into my model, but failed.
the error message says :
The method '[]' was called on null, tried calling : []("alamat")
Here is my codes :
Repositories :
Future<FaskesModel> getFaskesFirestore(String id) async {
var result = _firestore
.collection("fakses")
.doc(id)
.get()
.then((snapshot) => FaskesModel.fromSnapshot(snapshot));
return result;
}
Class FaskesModel :
import 'package:cloud_firestore/cloud_firestore.dart';
class FaskesModel {
String alamat;
String id;
String nama;
GeoPoint alamatGeo;
String deskripsi;
String noTelepon;
String noTeleponDarurat;
String urlGambar;
String website;
FaskesModel(
{this.alamat,
this.alamatGeo,
this.deskripsi,
this.id,
this.nama,
this.noTelepon,
this.noTeleponDarurat,
this.urlGambar,
this.website});
factory FaskesModel.fromJson(Map<String, dynamic> json) => FaskesModel(
alamat: json['alamat'] as String,
alamatGeo: json['alamatGeo'] as GeoPoint,
deskripsi: json['deskripsi'] as String,
id: json['id'] as String,
nama: json['nama'] as String,
noTelepon: json['noTelepon'] as String,
noTeleponDarurat: json['noTeleponDarurat'] as String,
urlGambar: json['urlGambar'] as String,
website: json['website'] as String);
Map<String, dynamic> toJson() => {
"alamat": alamat,
"alamatGeo": alamatGeo,
"deskripsi": deskripsi,
"id": id,
"nama": nama,
"noTelepon": noTelepon,
"noTeleponDarurat": noTeleponDarurat,
"urlGambar": urlGambar,
"website": website
};
FaskesModel.fromSnapshot(DocumentSnapshot documentSnapshot)
: alamat = documentSnapshot.data()['alamat'],
alamatGeo = documentSnapshot.data()['alamatGeo'],
deskripsi = documentSnapshot.data()['deskripsi'],
id = documentSnapshot.data()['id'],
nama = documentSnapshot.data()['nama'],
noTelepon = documentSnapshot.data()['noTelepon'],
noTeleponDarurat = documentSnapshot.data()['noTeleponDarurat'],
urlGambar = documentSnapshot.data()['urlGambar'],
website = documentSnapshot.data()['urlGambar'];
}
and in the class Bloc, i just call like this :
FaskesModel faskesModel =
await _firebaseRepository.getFaskesFirestore(event.id);
I have searched at another questions, i found to get the DataSnapshot field, just call snapShot.data.data but in my case i just found snapShot.data().
Once again, the point of my question is How to fetch data from Firestore into FaskesModel
I thank you.
Posting this as Community Wiki, based in the comments.
It seems that the issue was related to a mistyping in the collection's name, when returning the data using a snapshot, to the class. Once the type was correct, the return of data worked correctly and there was no more null being printed.