New to flutter, following tutorial to convert txt and image to Json, anyone tell me whats wrong with the code?

Viewed 19

Creating an app for a school project, trying to use JSON to save text and image, but the tutorial I'm using is appearing to be incorrect, any help is useful.

import 'dart:io';

import 'package:path_provider/path_provider.dart';

class FileManager {
  static late FileManager _instance;

  FileManager._internal() {
    _instance = this;
  }

  factory FileManager() => _instance ?? FileManager.internal();

  Future<String> get _directoryPath async {
    Directory? directory = await getExternalStorageDirectory();
    return directory!.path;
  }

  Future<File> get _file async {
    final path = await _directoryPath;
    return File('$path/blog.txt');
  }
}

FileManager.internal(); on line 12 is underlined with the message:

The left operand can't be null, so the right operand is never executed. Try removing the operator and the right operand.dartdead_null_aware_expression The method 'internal' isn't defined for the type 'FileManager'.

Try correcting the name to the name of an existing method, or defining a method named 'internal'.

1 Answers

You are using not nullable data and promising that you will assign data before read time and it will never get null static late FileManager _instance;

So, providing default value on null cases will never happen. you can make it nullable then ?? work for null case.

  static FileManager? _instance;
class FileManager {
  static late FileManager _instance; //promising value assing before read time

I think you want like this

class FileManager {
  static FileManager? _instance;

  FileManager._internal() {
    _instance = this;
  }

  factory FileManager() => _instance ?? FileManager._internal();

Related