2021-08-31

Unhandled Exception: Null check operator used on a null value in insert method

My app is a todo app, and I need to use a local database, I used sqflite lib and path lib, and i have some obstacles. in the main.dart:

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  final database=openDatabase(
      join(await getDatabasesPath(),'todo.db'),
    onCreate: (db,version){
        return db.execute('Create table todos(id INTEGER, title TEXT, dateTime DateTime, timeOfDay TimeOfDay)');
    },
    version: 1,
  );
  runApp(MyApp());
} 

in Add Todo screen i have a task title ,a date time and a time of day and i have a button to save this information into the database by this code:

TextButton(
              onPressed: ()async{
                  await insertTodo(Todo(0, 'num1', selectedDate , selectedTime));
                  //save();

              },

selectTime(BuildContext context)async{
    final TimeOfDay? selectedT=await showTimePicker(
        context: context,
        initialTime: selectedTime,

    );
    if(selectedT !=null && selectedT!=selectedTime){
      setState(() {
        selectedTime=selectedT;
      });
    }
    return selectedTime;
  }

  selectDate(BuildContext context)async{
    final DateTime? selected=await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2010),
        lastDate: DateTime(2025),
    );

    if(selected !=null && selected!=selectedDate){
      setState(() {
        selectedDate=selected;
      });
    }
    return selectedDate;
  }

in todo class :

import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:todo_appv2/addTaskScreen.dart';
import 'package:todo_appv2/addTaskScreen.dart';

class Todo{
   final int id;
   final String title;
   final DateTime? dateTime;
   final TimeOfDay? timeOfDay;

  Todo(this.id, this.title, this.dateTime, this.timeOfDay,);
  
  Map<String,Object> toMap(){
    
    print('this is my $id value');
    return{
      'id':id,
      'title':title,
      'dateTime':dateTime!,
      'timeOfDay':timeOfDay!,
    };
  }

  @override
  String toString(){
    return 'Todo{id: $id, title: $title, dateTime:$dateTime, timeOfDay:$timeOfDay}';
  }

}

Future<void> insertTodo(Todo todo)async{
  final db= database;
  await db!.insert('todos', todo.toMap(),conflictAlgorithm: ConflictAlgorithm.replace);
}

when i run my app and tap to text button there is an error: ==> Unhandled Exception: Null check operator used on a null value the error from insertTodo Function , from todo.toMap() but i don't now why there is an error and how i fix it, please any help :\



from Recent Questions - Stack Overflow https://ift.tt/3yoFwVW
https://ift.tt/eA8V8J

No comments:

Post a Comment