I am a beginner in Flutter development, I have problems regarding "GET" image from the API because there are different fields which makes my application error when the user doesn’t have an "image" in his account.
The error is like this:
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building Consumer<ProfileUserController>(dirty, dependencies: [_InheritedProviderScope<ProfileUserController?>]):
The method '[]' was called on null.
Receiver: null
Tried calling: []("previewUrl")
here is my code :
// ProfileDetailUser
class ProfileDetailUser extends StatefulWidget {
const ProfileDetailUser({super.key});
@override
State<ProfileDetailUser> createState() => _ProfileDetailUserState();
}
class _ProfileDetailUserState extends State<ProfileDetailUser> {
String? _selectedImagePath;
bool _dataInitialized = false;
final UpdateUserController updateController = UpdateUserController();
void _handleImageSelected(String filePath) {
setState(() {
_selectedImagePath = filePath;
updateController.setImagePath(filePath);
// updateController.imageController.text = filePath;
});
debugPrint('File path: $filePath');
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => ProfileUserController(),
child: Consumer<ProfileUserController>(
builder: (context, profileController, child) {
if (profileController.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (profileController.userData == null) {
return ErrorScreen(onRetry: profileController.retryFetchUserData);
}
// Initialize UpdateUserController's text controllers with data from ProfileUserController
if (!_dataInitialized) {
// Check whether the image is null or not before accessing previewUrl
var image = profileController.userData!['biodate']['image'];
if (image != null && image['previewUrl'] != null) {
updateController.imageController.text =
image['previewUrl'].replaceAll("localhost", "1.1.1.1");
} else {
updateController.imageController.text = '';
}
_dataInitialized = true;
}
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0,
title: Text(
'Profile',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
body: Container(
color: Colors.grey.shade100,
child: SingleChildScrollView(
padding: const EdgeInsets.only(
left: 16, right: 16, top: 16, bottom: 30),
child: Column(
children: [
UserAvatarField(
onFileSelected: _handleImageSelected,
imagePath: _selectedImagePath ??
profileController.userData!['biodate']['image']
['previewUrl']
?.replaceAll("localhost", "1.1.1.1"),
),
....
rest of my code
//UserAvatarField
class UserAvatarField extends StatelessWidget {
final void Function(String filePath) onFileSelected;
final String? imagePath;
const UserAvatarField(
{super.key, required this.onFileSelected, this.imagePath});
void _pickFile(BuildContext context) async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'jpeg', 'png'],
);
if (result != null && result.files.isNotEmpty) {
final file = result.files.first;
if (file.size <= 5 * 1024 * 1024) {
final imageBytes = File(file.path!).readAsBytesSync();
final image = img.decodeImage(imageBytes);
if (image != null && image.width == 300 && image.height == 300) {
onFileSelected(file.path!);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Berhasil Menambahkan Image')),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Image harus berukuran 300x300 pixels')),
);
}
} else {
// Show error message if file size exceeds 5MB
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('File size exceeds 5MB')),
);
}
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => _pickFile(context),
child: Container(
padding: const EdgeInsets.all(4), // Border width
decoration: BoxDecoration(
color: Colors.grey.shade200, // Border color
shape: BoxShape.circle,
),
child: CircleAvatar(
radius: 50,
backgroundColor: Colors.white,
backgroundImage: imagePath != null && imagePath!.isNotEmpty
? (imagePath!.startsWith('http')
? NetworkImage(imagePath!)
: FileImage(File(imagePath!))) as ImageProvider
: null,
child: imagePath == null || imagePath!.isEmpty
? Icon(CupertinoIcons.camera_fill,
size: 50, color: Colors.grey.shade500)
: null,
),
),
);
}
}
then this is the output from the api if the user does not have an image like this:
{
"id": "717102e2",
"email": "[email protected]",
"biodate": {
"image": null
}
}
but if the image exists then the API output is like this:
{
"id": "717102e2",
"email": "[email protected]",
"biodate": {
"image": {
"downloadUrl": "http://localhost/file/1723013762907-208412624.png",
"previewUrl": "http://localhost/file/1723013762907-208412624.png"
},
}
}
there are field differences that make it difficult for me to do conditioning to check whether the image is there or not,
I have tried to make changes to my code but it doesn’t work, can anyone help me to find the solution of my problem ?
2
Answers
To make it simple, You can create a model class for you json response.
I have used quicktype for creating model classes from json.
UserModel.dart
In this model class, I am assuming that in the json, if the "image" is not null then the "download" and "preview" url will definitely be there. So, I created Image model with required parameters. Otherwise, you can uncomment the Image model with optional parameter class.
Now, you can convert your response into UserModel. Here’s an example
//Based on if condition you can check if the image is not null and then you can show or hide it.
you need to check if the image field is null before trying to use it. Here’s how you can manage this in your Flutter code:
Make a network request to get the user data.
Parse the JSON response.
Check if the image field is null.
Display the image if it exists, otherwise display a placeholder.