Exception caught by widgets library LateInitializationError: Field '_profileImage@88500975' has not been initialized

Viewed 33

hello every one I got this error on my code when I defined the _profileImage and _bannerImage it appears a red line so I should put a late modifier before them when I put a late modifier the error appears on the title of the question appears to me. I can't move the late modifier and put a ? because it will reflect on the _profileImage and _bannerImage on the rest of the code that I should put a ! , but I don't want to but it because _profileImage and _bannerImage can be null if they are null the icon person will appears instead of them

here is my code

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:insight_software/other_screen/user.dart';

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

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

class _EditPageState extends State<EditPage> {
  bool showPassword = false;
  UserService _userService = UserService();
  late File _profileImage;
  late File _bannerImage;
  final picker = ImagePicker();
  String name = '';

  Future getImage(int type) async {
    // to pick a picture from the camera
    final pickedFile = await picker.getImage(source: ImageSource.camera);
    // to pick a picture from the stodio
    // final pickedFile2 = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      if (pickedFile != null && type == 0) {
        _profileImage = File(pickedFile.path);
      }

      // if (pickedFile2 != null && type == 0) {
      //   _profileImage = File(pickedFile2.path);
      // }

      if (pickedFile != null && type == 1) {
        _bannerImage = File(pickedFile.path);
      }

      // if (pickedFile2 != null && type == 1) {
      //   _bannerImage = File(pickedFile2.path);
      // }
    });
  }

  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        title: new Text('edit profile'),
      ),
      body: Container(
        padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
        child: new Form(
          child: Column(
            children: [
              FlatButton(
                onPressed: () => getImage(0),
                child: _profileImage == null
                    ? Icon(Icons.person)
                    : Image.file(
                        _profileImage,
                        height: 100,
                      ),
              ),
              SizedBox(height: 40),
              FlatButton(
                onPressed: () => getImage(1),
                child: _bannerImage == null
                    ? Icon(Icons.person)
                    : Image.file(
                        _profileImage,
                        height: 100,
                      ),
              ),
              SizedBox(height: 40),
              TextFormField(
                decoration: InputDecoration(
                  hintText: " Name",
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25),
                  ),
                ),
                onChanged: (val) => setState(() {
                  name = val;
                }),
              ),
              SizedBox(
                height: 35,
              ),
              Container(
                padding: EdgeInsets.all(0),
                child: new ConstrainedBox(
                  constraints: BoxConstraints(
                    maxHeight: 220.0,
                  ),
                  child: new Scrollbar(
                    child: new SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      reverse: true,
                      child: SizedBox(
                        height: 150,
                        child: new TextField(
                          maxLines: 100,
                          decoration: new InputDecoration(
                            border: InputBorder.none,
                            hintText: 'About',
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  OutlineButton(
                    padding: EdgeInsets.symmetric(horizontal: 50),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20)),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text("CANCEL",
                        style: TextStyle(
                            fontSize: 14,
                            letterSpacing: 2.2,
                            color: Colors.black)),
                  ),
                  FlatButton(
                    onPressed: (() async {
                      await _userService.updateprofile(
                          _bannerImage, _profileImage, name);
                      Navigator.pop(context);
                    }),
                    color: Colors.lightBlue,
                    padding: EdgeInsets.symmetric(horizontal: 50),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20)),
                    child: Text(
                      "SAVE",
                      style: TextStyle(
                          fontSize: 14,
                          letterSpacing: 2.2,
                          color: Colors.white),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

please help me what I can do?

1 Answers

If _profileImage and _bannerImage can be null, change their types from "late File" to just "File?". The "?" means that they can either be of type "File", or have a null value. If the type is "File", that means they can't have a null value.

So just change

late File _profileImage;
late File _bannerImage;

to

File? _profileImage;
File? _bannerImage;

You can read up on null safety in dart to better understand what's happening here.

Edit to show how to use the variables:

Now, if you want to use _profileImage somewhere, you can either specify that you know it's not a null value by using _profileImage!, or you can provide an alternative when it's null, like so:

someValue = _profileImage ?? Image("substituteImage.png");

If you want to access some member of _profileImage, you can also do:

_profileImage?.resize();
Related