Search code examples
flutterdartsqflite

Flutter can't access data because it's potentially null


How can I define my function nullable? I get the following error on Flutter (InsertData is the function in repository.dart):

`lib/services/categoriesservices.dart:13:30: Error: Property 'InsertData' cannot be accessed on 'Repository?' because it is potentially null.

'Repository' is from 'package:sqflite2/repositories/repository.dart' ('lib/repositories/repository.dart'). Try accessing using ?. instead. return await _repository.InsertData.call(`

repository.dart seen below:

import 'package:sqflite/sqflite.dart';
import 'package:sqflite2/repositories/databaseconnection.dart';

class Repository {
  DataBaseConnection? _dataBaseConnection;

  Repository() {
    //initialize database connection
    _dataBaseConnection = DataBaseConnection();
  }

  static Database? _database;
  Future<Database?> get database async {
    if (_database != null) {
      return _database;
    }
    _database = await _dataBaseConnection.setDatabase();
    return database;
  }

  //create function inserting data to database
  InsertData(table, data) async {
    var connection = await database;
    return await connection.insert(table, data);
  }
}

The function is initialized as seen below:

import 'package:sqflite2/models/category.dart';
import 'package:sqflite2/repositories/repository.dart';

class CategoryService {
  Repository? _repository;

  CategoryService() {
    _repository = Repository();
  }

  saveCategory(Categori category) async {
    return await _repository.InsertData("categories", category.categoryMap());
  }
}

What am I missing ? I thought I already initiliazed the Repository with (?)


Solution

  • You need to access the member functions, variables of your nullable object with ? operator. Just declaring nullable will not satisfy the compiler. It can be null while accessing insertData function.

    It performs a null check before accessing the function.

    Try the below snippet with ? operator.

    saveCategory(Categori category) async {
        return await _repository?.InsertData("categories", category.categoryMap());
      }
    

    If you are certain that _repository object is not null while accessing the saveCategory(Categori category) function. You can use ! operator for force assurance that the object is not null (Not recommended).

    return await _repository!.InsertData("categories", category.categoryMap());
    

    You might also wanna look at late modifier

    About nullable function

    Return values

    All functions return a value. If no return value is specified, the statement return null; is implicitly appended to the function body.

    Therefore, if you know the return type of your function, specify it. If the function may return null, use '?' after the return type.