'Field '_image' has not been initialized in flutter

I wastrying image upload in flutter using imagepicker. While I was choose image the image cant display in one container. I was no error in error console. But the error was"Field '_image' has not been initialized. I am confused in flutter. Please he me guys

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  File? _image;
  final picker = ImagePicker();
  TextEditingController namecontroller = TextEditingController();
  Future chooseimage() async {
    var pickedImage = await picker.pickImage(source: ImageSource.gallery);
    setState(() {
      //_image = File(pickedImage!.path);
      _image = File(pickedImage!.path);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Upload Image"),
      ),
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: chooseimage,
                child: Text("Select Image"),
                style: ElevatedButton.styleFrom(primary: Colors.green),
              ),
              TextField(
                controller: namecontroller,
                decoration: InputDecoration(label: Text("Name")),
              ),
              SizedBox(
                height: 30.0,
              ),
              ElevatedButton(
                onPressed: () {},
                child: Text("Upload"),
                style: ElevatedButton.styleFrom(primary: Colors.blue),
              ),
              Container(
                child: _image == null
                    ? Text('No Image Select')
                    : Image.file(_image!),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Solution 1:[1]

///You can take a reference through this code hope this will work for you. Thanks
    
        
    import 'dart:io';
    import 'package:cached_network_image/cached_network_image.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_spinkit/flutter_spinkit.dart';
    import 'package:image_cropper/image_cropper.dart';
    import 'package:image_picker/image_picker.dart';
    import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
    import 'package:provider/provider.dart';
    import 'package:traveling/Provider/EmployeeProvider/EmployeeProfileProvider.dart';
    import 'package:traveling/helpers/AppColors.dart';
    ///To get the crop value creating a class
    enum AppState {
      free,
      picked,
      cropped,
    }
    class EmployeeProfile extends StatefulWidget {
      final bool leadingIcon;
      final number;
      final cardName;
    
      EmployeeProfile(
          {Key? key, required this.leadingIcon, this.number, this.cardName})
          : super(key: key);
    
      @override
      _EmployeeProfileState createState() => _EmployeeProfileState();
    }
    
    class _EmployeeProfileState extends State<EmployeeProfile>
        with TickerProviderStateMixin {
      EmployeeProfileProvider? _provider;
      ///controller widget used in Spinkit plugin to show loading process
      animationControllerField(){
        AnimationController animationController =AnimationController(
            vsync: this, duration: const Duration(milliseconds: 900));
      }
    
      bool? visible;
      double? _width;
      File? _image;
      var url;
      late AppState state;
      final picker = ImagePicker();
    
    
    
      ///pop-up to choose camera gallery while uploading image
      Future<void> _showChoiceDialog(BuildContext context) {
        return showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(
                  "Choose option",
                  style: TextStyle(color: AppColors.hotelListDarkBlue),
                ),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: [
                      Divider(
                        height: 1,
                        color: AppColors.baseLightBlueColor,
                      ),
                      ListTile(
                        onTap: () {
                          Navigator.pop(context, _pickImage(ImageSource.gallery,context));
                        },
                        title: Text(
                          "Gallery",
                          style: TextStyle(color: AppColors.hotelListDarkBlue),
                        ),
                        leading: Icon(
                          Icons.account_box,
                          color: AppColors.baseLightBlueColor,
                        ),
                      ),
                      Divider(
                        height: 1,
                        color: AppColors.baseLightBlueColor,
                      ),
                      ListTile(
                        onTap: () {
                          Navigator.pop(context, _pickImage(ImageSource.camera,context));
                        },
                        title: Text(
                          "Camera",
                          style: TextStyle(color: AppColors.hotelListDarkBlue,),
                        ),
                        leading: Icon(
                          Icons.camera,
                          color: AppColors.baseLightBlueColor,
                        ),
                      ),
                    ],
                  ),
                ),
              );
            });
      }
      ///crop image selecting by the user
      Future<Null> _cropImage() async {
        File? croppedFile = await ImageCropper.cropImage(
            sourcePath: _image!.path,
            aspectRatioPresets: Platform.isAndroid
                ? [
              CropAspectRatioPreset.square,
              CropAspectRatioPreset.ratio3x2,
              CropAspectRatioPreset.original,
              CropAspectRatioPreset.ratio4x3,
              CropAspectRatioPreset.ratio16x9
            ]
                : [
              CropAspectRatioPreset.original,
              CropAspectRatioPreset.square,
              CropAspectRatioPreset.ratio3x2,
              CropAspectRatioPreset.ratio4x3,
              CropAspectRatioPreset.ratio5x3,
              CropAspectRatioPreset.ratio5x4,
              CropAspectRatioPreset.ratio7x5,
              CropAspectRatioPreset.ratio16x9
            ],
            androidUiSettings: AndroidUiSettings(
                toolbarTitle: 'Cropper',
                toolbarColor: AppColors.baseLightBlueColor,
                toolbarWidgetColor: Colors.white,
                initAspectRatio: CropAspectRatioPreset.original,
                lockAspectRatio: false),
            iosUiSettings: IOSUiSettings(
              title: 'Cropper',
            ));
        if (croppedFile != null) {
          _image = croppedFile;
          setState(() {
            state = AppState.cropped;
          });
          ///to get upload image
          url = await  _provider!.setUserUpdatedImageInfo(_image!, );
          setState(() {
            ///to set the image
            _provider!.currentLoggedInUser!.image = url;
    
          });
        }
      }
      ///icon change while user edit image
      Widget _buildButtonIcon() {
        if (state == AppState.free)
          return Icon(
            MdiIcons.squareEditOutline,
            color: AppColors.popUpBlueColor,
            size: 20,
          );
        else if (state == AppState.picked)
          return Icon(Icons.crop,color: AppColors.popUpBlueColor,
            size: 20,);
        else if (state == AppState.cropped)
          return Icon(
            MdiIcons.squareEditOutline,
            color: AppColors.popUpBlueColor,
            size: 20,
          );
        else
          return Container();
      }
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        print("initState called");
        state = AppState.free;
        _provider = EmployeeProfileProvider();
        _provider!.getUserInfo();
      }
    
      ///this widget is the main widget and it is used for building a UI in the app.
      @override
      Widget build(BuildContext context) {
        _width = MediaQuery.of(context).size.width;
        return ChangeNotifierProvider<EmployeeProfileProvider?>(
            create: (context) => _provider!,
            child: Consumer<EmployeeProfileProvider?>(
                builder: (context, provider, child) {
                  return provider!.currentLoggedInUser==null?
                  Material(
                    color: AppColors.white,
                    child: Center(
                      child:
                      SpinKitCubeGrid(
                          color: AppColors.baseLightBlueColor,
                          size: 50.0,
                          controller:animationControllerField()
                      ),
                    ),
                  ):Container(
                    width: _width!,
                    color: AppColors.white,
                    child: Stack(
                      children: [
                        Column(
                          children: [
                            Material(
                              color: AppColors.baseLightBlueColor,
                              elevation: 15,
                              shape: RoundedRectangleBorder(
                                borderRadius:
                                BorderRadius.only(bottomRight: Radius.circular(30)),
                              ),
                              child: Container(
                                height: 180,
                                decoration: BoxDecoration(
                                  color: AppColors.baseLightBlueColor,
                                  // AppColors.blue,
                                  borderRadius: BorderRadius.only(
                                      bottomRight: Radius.circular(30)),
                                ),
                              ),
                            ),
                          ],
                        ),
                        Positioned(
                            top: 80,
                            child:
    
                            Stack(
                              children: [
                                Container(
                                  height: 150,
                                  width: _width,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      CachedNetworkImage(
                                        filterQuality: FilterQuality.high,
                                        maxHeightDiskCache: 100,
                                        fit: BoxFit.cover,
                                        imageUrl: provider.currentLoggedInUser!.image.toString(),
                                        imageBuilder: (context, imageProvider) => Container(
                                          height: 120,
                                          width: 120,
                                          decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            image: DecorationImage(
                                                image: imageProvider, fit: BoxFit.cover),
                                            border: Border.all(
                                                color: AppColors.white, width: 2.0),
    
                                          ),
                                        ),
    
                                        placeholder: (context, url) =>
                                        const CircularProgressIndicator(),
                                        errorWidget: (context, url, error) => Container(
                                          height: 120,
                                          width: 120,
                                          decoration: BoxDecoration(
                                            color: Colors.white,
                                            shape: BoxShape.circle,
                                            image:DecorationImage(
                                                fit: BoxFit.cover,
                                                image: AssetImage('assets/managerPicture.jpeg')),
                                            border: Border.all(
                                                color: AppColors.white, width: 2.0),
                                          ),
                                        ),
                                        fadeOutDuration: const Duration(seconds: 1),
                                        fadeInDuration: const Duration(seconds: 3),
                                      ),
                                    ],
                                  ),
                                ),
                                Positioned(
                                  top: 60,
                                  right: 0,
                                  left: 100,
                                  bottom: 0,
                                  child: GestureDetector(
                                    onTap: () {
                                      if (state == AppState.free)
                                        _showChoiceDialog(context);
                                      else if (state == AppState.picked)
                                        _cropImage();
                                      else if (state == AppState.cropped) _showChoiceDialog(context);
                                    },
                                    child: Container(
                                      height: 10,
                                      width: _width,
                                      child: Row(
                                        mainAxisAlignment:
                                        MainAxisAlignment.center,
                                        children: [
                                          Container(
                                            height: 35,
                                            width: 35,
                                            decoration: BoxDecoration(
                                              color:
                                              AppColors.profiePicBackground,
                                              borderRadius:
                                              BorderRadius.circular(60),
                                            ),
                                            child: ClipRRect(
                                              borderRadius:
                                              BorderRadius.circular(60.0),
                                              child: _buildButtonIcon(),
                                              /*Icon(
                                                          MdiIcons.squareEditOutline,
                                                          color: AppColors.popUpBlueColor,
                                                          size: 20,
                                                        ),*/
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            )
                        ),
                        Positioned(
                            top: 40,
                            child: Container(
                              width: MediaQuery.of(context).size.width,
                              padding: EdgeInsets.only(left: 8, right: 8),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  widget.leadingIcon == true
                                      ? Align(
                                    alignment: Alignment.topLeft,
                                    child: GestureDetector(
                                        onTap: () {
                                          Navigator.pop(context);
                                        },
                                        child: Icon(
                                          MdiIcons.arrowLeft,
                                          color: Colors.white,
                                        )),
                                  )
                                      : Container(),
                                  
                                ],
                              ),
                            )),
                      ],
                    ),
                  );
                }));
      }
      ///ImageSource: Camera and Gallery.
      Future<Null> _pickImage(ImageSource source,context) async {
        final pickedImage = await ImagePicker().pickImage(source: source);
        _image = pickedImage != null ? File(pickedImage.path) : null;
        if (_image != null) {
          setState(() {
            state = AppState.picked;
    
    
          });
    
        }
      }
    
    
    }
    
    class EmployeeProfileProvider extends ChangeNotifier {
      late bool _isInfoEditable;
      FirebaseFirestore? fireStoreInstance;
      EmployeeProfileModel? _userData;
      // EmployeeMyExpenseReport ? _employeeMyExpenseReport;
      ///to update the employee profile image
      Future<String?> setUserUpdatedImageInfo(File _image, ) async {
        var data=  await EmployeeServices.getInstance().uploadImageToFirebase(_image, );
        notifyListeners();
        return data;
      }
      ///to update Personal details of employee
      EmployeeProfileModel? get getUploadedImage => _userData;
      @override
      void dispose() {
        //print("Provider disposed called");
        super.dispose();
      }
      //upload employee image on firebase
      String ?url;
      Future <String?>uploadImageToFirebase(File _image) async {
        User? currentUser = FirebaseAuth.instance.currentUser;
        String fileName = basename(_image.path);
        firebase_storage.Reference ref = firebase_storage.FirebaseStorage.instance
            .ref().child('uploads')
            .child('/$fileName');
        final metadata = firebase_storage.SettableMetadata(
            contentType: 'image/jpeg',
            customMetadata: {'picked-file-path': fileName});
        firebase_storage.UploadTask uploadTask;
        uploadTask = ref.putFile(io.File(_image.path), metadata);
        //String ?url;
        await uploadTask.whenComplete(() async {
          url = await uploadTask.snapshot.ref.getDownloadURL();
        });
        Future.value(uploadTask)
            .then((value) => {
          print("Upload file path ${value.ref.fullPath}"),
          FirebaseFirestore.instance.collection(FirestoreCollections.employees).doc(currentUser!.uid).update({'image': '$url'}),
        })
            .onError((error, stackTrace) =>
        {
          print("Upload file path error ${error.toString()} ")}
        );
        return url;
      }
    
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vishal_VE