skip to Main Content

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


  1. 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

    import 'dart:convert';
    
    
    UserModel userModelFromJson(String str) => UserModel.fromJson(json.decode(str));
    
    String userModelToJson(UserModel data) => json.encode(data.toJson());
    
    class UserModel {
        final String id;
        final String email;
        final Biodate biodate;
    
        UserModel({
            required this.id,
            required  this.email,
           required this.biodate,
        });
    
        factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
            id: json["id"],
            email: json["email"],
            biodate: Biodate.fromJson(json["biodate"]),
        );
    
        Map<String, dynamic> toJson() => {
            "id": id,
            "email": email,
            "biodate": biodate?.toJson(),
        };
    }
    
    class Biodate {
        Image? image;
    
        Biodate({
            this.image,
        });
    
        factory Biodate.fromJson(Map<String, dynamic> json) => Biodate(
            image: json["image"] == null ? null : Image.fromJson(json["image"]),
        );
    
        Map<String, dynamic> toJson() => {
            "image": image?.toJson(),
        };
    }
    
    //Image model with optional parameters
    // class Image {
    //   String? downloadUrl;
    //   String? previewUrl;
    //   Image({
    //     this.downloadUrl,
    //      this.previewUrl,
    //   });
    
    //   factory Image.fromJson(Map<String, dynamic> json) => Image(
    //         downloadUrl: json["downloadUrl"],
    //         previewUrl: json["previewUrl"],
    //       );
    
    //   Map<String, dynamic> toJson() => {
    //         "downloadUrl": downloadUrl,
    //         "previewUrl": previewUrl,
    //       };
    // }
    
    //Image model with required parameters
    class Image {
        final String downloadUrl;
        final String previewUrl;
    
        Image({
            required this.downloadUrl,
            required this.previewUrl,
        });
    
        factory Image.fromJson(Map<String, dynamic> json) => Image(
            downloadUrl: json["downloadUrl"],
            previewUrl: json["previewUrl"],
        );
    
        Map<String, dynamic> toJson() => {
            "downloadUrl": downloadUrl,
            "previewUrl": previewUrl,
        };
    }
    
    
    

    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

    
    void main() {
      String responseBody = '''
      {
        "id": "717102e2",
        "email": "[email protected]",
        "biodate": {
          "image": {
            "downloadUrl": "http://localhost/file/1723013762907-208412624.png",
            "previewUrl": "http://localhost/file/1723013762907-208412624.png"
          }
        }
      }
      ''';
    
      UserModel user = userModelFromJson(responseBody);
    
      print("user: $user");
    
      if (user.biodate != null && user.biodate?.image != null) {
        print("preview: ${user.biodate?.image?.previewUrl}");
        print("downLoad: ${user.biodate?.image?.downloadUrl}");
      }
    
    
    }
    

    //Based on if condition you can check if the image is not null and then you can show or hide it.

    Login or Signup to reply.
  2. 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.

    FutureBuilder<Map<String, dynamic>>(
            future: fetchUserData(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(child: CircularProgressIndicator());
              } else if (snapshot.hasError) {
                return Center(child: Text('Error: ${snapshot.error}'));
              } else if (snapshot.hasData) {
                var userData = snapshot.data!;
                var imageUrl = userData['biodate']['image'] != null
                    ? userData['biodate']['image']['downloadUrl']
                    : null;
    
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      imageUrl != null
                          ? Image.network(imageUrl)
                          : Placeholder(
                              fallbackHeight: 100,
                              fallbackWidth: 100,
                            ),
                      SizedBox(height: 20),
                      Text(userData['email']),
                    ],
                  ),
                );
              }
              return Container();
            },
          ),
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search