0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flutter image_pickerで最初に遭遇するエラー Failed assertion: line 853 pos 14: 'file != null': is not true.

Posted at

画像が必ずセットされていないとエラーになる

初めてimage_pickerを使ってみると、大体発生するエラー。。。:disappointed:

こういうコードの場合、画像が何も選択されていないからエラーが発生します


════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/painting/image_provider.dart': Failed assertion: line 853 pos 14: 'file != null': is not true.
The relevant error-causing widget was
UserImagePicker
lib/…/auth/auth_form.dart:60
════════════════════════════════════════════════════════════════════════════════
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class UserImagePicker extends StatefulWidget {
  @override
  _UserImagePickerState createState() => _UserImagePickerState();
}

class _UserImagePickerState extends State<UserImagePicker> {
  File _pickedImage;
  void _pickImage() async {
    final pickedImage =
        await ImagePicker().getImage(source: ImageSource.gallery);
    final pickedImageFile = File(pickedImage.path);
    setState(() {
      _pickedImage = pickedImageFile;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        CircleAvatar(
          radius: 40,
          backgroundImage: FileImage(_pickedImage),
        ),
        TextButton.icon(
          onPressed: _pickImage,
          icon: Icon(Icons.image),
          label: Text(
            'Add Image',
            style: TextStyle(color: Theme.of(context).primaryColor),
          ),
        ),
      ],
    );
  }
}

「nullの場合」を追加するだけで解決!

もしnullじゃなければ左(FileImage(_pickedImage)、nullなら右(null

と言うような処理で解決です!

 CircleAvatar(
          radius: 40,
          backgroundImage:
              _pickedImage != null ? FileImage(_pickedImage) : null,
        ),
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?