Home > Mobile >  New to flutter and unsure how to solve this error: Exception has occurred. LateError
New to flutter and unsure how to solve this error: Exception has occurred. LateError

Time:08-18

Getting the error message: 'Exception has occurred. LateError (LateInitializationError: Field 'selectedImage' has not been initialized'

Anyone know how I can solve this?

Been following a tutorial to build an app that I can add photos to but got a bit stuck on this part.

using firebase storage to store the photos, as far as I can tell thats been set up correctly.

thanks.

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

@override
State<CreateBlog> createState() => _CreateBlogState();
}

class _CreateBlogState extends State<CreateBlog> {
String? authorName, title, desc;

File? selectedImage;
CrudMethods crudMethods = CrudMethods();

Future getImage() async {
var image = await ImagePicker().pickImage(source: ImageSource.camera);

setState(() {
  selectedImage = image as File;
 });
}

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: const <Widget>[
        Text(
          'Travel',
          style: TextStyle(fontSize: 22),
        ),
        Text('Blog', style: TextStyle(fontSize: 22, color: Colors.green))
      ],
    ),
    backgroundColor: Colors.transparent,
    elevation: 0.0,
    actions: <Widget>[
      GestureDetector(
          onTap: () {
            getImage();
          },
          child: selectedImage != null
              ? Container(
                  height: 150,
                  width: MediaQuery.of(context).size.width,
                  child: Image.file(selectedImage),
                  margin: const EdgeInsets.symmetric(horizontal: 16),
                )
              : Container(
                  margin: const EdgeInsets.symmetric(horizontal: 16),
                  child: const Icon(Icons.add))),
    ],
   ),
   body: Container(
    padding: const EdgeInsets.symmetric(horizontal: 15),
    child: Column(
      children: <Widget>[
        const SizedBox(height: 12),
        Container(
            height: 150,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(6),
            ),
            width: MediaQuery.of(context).size.width,
            child: const Icon(Icons.add_a_photo, color: Colors.black45)),
        const SizedBox(height: 8),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Column(
            children: <Widget>[
              TextField(
                decoration: const InputDecoration(hintText: 'Author Name'),
                onChanged: (val) {
                  authorName = val;
                },
              ),
              TextField(
                decoration: const InputDecoration(hintText: 'Title'),
                onChanged: (val) {
                  title = val;
                },
              ),
              TextField(
                  decoration:
                      const InputDecoration(hintText: 'Description'),
                  onChanged: (val) {
                    desc = val;
                  }),
            ],
          ),
        )
      ],
    ),
  ),
);
}
}

CodePudding user response:

It is possible to get null value from pickedImage, Try accepting null value.

Future getImage() async {
  XFile? image = await ImagePicker().pickImage(source: ImageSource.camera);
  if (image != null) {
    setState(() {
      selectedImage = image;
    });
  }
}

And use

child: selectedImage != null
    ? Container(
        height: 150,
        width: MediaQuery.of(context).size.width,
        child: Image.file(File(selectedImage!.path)),
        margin: const EdgeInsets.symmetric(horizontal: 16),
      )

CodePudding user response:

The error really implies that you wrote

late File? selectedImage;

instead of

File? selectedImage;

so I think you showed us the wrong code. Leaving out late should solve this.

CodePudding user response:

Let me know whether it is working for you.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

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

  @override
  State<CreateBlog> createState() => _CreateBlogState();
}

class _CreateBlogState extends State<CreateBlog> {
  String? authorName, title, desc;
  XFile? selectedImage;

  getImage() async {
    try {
      final XFile? pickedImage =
          await ImagePicker().pickImage(source: ImageSource.gallery);
      if (pickedImage != null) {
        setState(() {
          selectedImage = pickedImage;
        });
      }
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const <Widget>[
            Text(
              'Travel',
              style: TextStyle(fontSize: 22),
            ),
            Text('Blog', style: TextStyle(fontSize: 22, color: Colors.black))
          ],
        ),
        backgroundColor: Colors.grey,
        elevation: 0.0,
      ),
      body: Container(
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Column(
          children: <Widget>[
            const SizedBox(height: 12),
            GestureDetector(
              onTap: () {
                getImage();
              },
              child: selectedImage != null
                  ? Container(
                      height: 150,
                      width: MediaQuery.of(context).size.width,
                      margin: const EdgeInsets.symmetric(horizontal: 16),
                      child: Image.file(File(selectedImage!.path)),
                    )
                  : Container(
                      height: 150,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(6),
                      ),
                      width: MediaQuery.of(context).size.width,
                      child:
                          const Icon(Icons.add_a_photo, color: Colors.black45)),
            ),
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Column(
                children: <Widget>[
                  TextField(
                    decoration: const InputDecoration(hintText: 'Author Name'),
                    onChanged: (val) {
                      authorName = val;
                    },
                  ),
                  TextField(
                    decoration: const InputDecoration(hintText: 'Title'),
                    onChanged: (val) {
                      title = val;
                    },
                  ),
                  TextField(
                      decoration:
                          const InputDecoration(hintText: 'Description'),
                      onChanged: (val) {
                        desc = val;
                      }),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
  • Related