Cannot Get Image from API in Flutter

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 ?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật