Home > front end >  Unhandled Exception: LateInitializationError: Field '_id@21016470' has not been initialize
Unhandled Exception: LateInitializationError: Field '_id@21016470' has not been initialize

Time:10-10

When i am running my project compiler is giving me this statement "LateInitializationError: Field 'Db' has" i am unable to fix this issue. When i execute the functions in dabase_client.dart i.e saveItem() function then it is creating issues and function Compiler is giving me direction that in some dart files there is an issue in code. I am going to provide you my Whole project code so that you can easily find out the exact problem which is creating an issue.

main.dart

import 'package:flutter/material.dart';
import 'package:no_to_do_app/ui/home.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'NotoDo',
      home: new Home(),
    );
  }
}

home.dart

import 'package:flutter/material.dart';
import 'package:no_to_do_app/ui/notodo_screen.dart';
class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text('NoToDo'),
        backgroundColor: Colors.black54,
      ),
      body: new NoToDoScreen(

      )
    );
  }
}

database_client.dart

import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:no_to_do_app/model/nodo_item.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelper
{
  static final DatabaseHelper _instance =  DatabaseHelper.private();
  DatabaseHelper.private();
  factory DatabaseHelper() => _instance;

  final String tableName = "nodoTbl";
  final String columnId = "id";
  final String columnItemName = "itemName";
  final String columnDateCreated = "dateCreated";

  static late Database _db;

  Future<Database> get database async
  {
    /*if(_db!=null)
      {
        return _db;
      }*/
    _db =await initDb();
    return _db;
  }

  DatabaseHelper.internal();

  initDb() async
  {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, "notodo_db.db");
    var ourDb= await openDatabase(path , version: 1 , onCreate: _onCreate);
    return ourDb;
  }

  void _onCreate(Database db, int version) async
  {
   await db.execute(
     "CREATE TABLE $tableName(id INTEGER PRIMARY KEY , $columnItemName TEXT ,$columnDateCreated TEXT)"
   );
   debugPrint('Table is Created');
  }

  Future<int> saveItem(NoDoItem item) async
  {
    var dbClient = await database;
    int res =await dbClient.insert(tableName, item.toMap());
    debugPrint(res.toString());
    return res;
  }

  Future<List> getItems() async
  {
    var dbClient = await database;
    var result = await dbClient.rawQuery("SELECT * FROM $tableName ORDER BY $columnItemName ASC");
    return result.toList();
  }

  Future<int?> getCount() async
  {
    var dbClient = await database;
    return Sqflite.firstIntValue(await dbClient.rawQuery(
        "SELECT COUNT(*) FROM $tableName"
    ));
  }

  Future<NoDoItem?> getItem(int id) async{
    var dbClient = await database;
    var result = await dbClient.rawQuery("SELECT * FROM $tableName WHERE id=$id");
    //if(result.length==0) return null;
    if(result.isEmpty) return null;
    return  NoDoItem.fromMap(result.first);
  }

  Future<int> deleteItem(int id) async
  {
    var dbClient =await database;
    return await dbClient.delete(tableName,where: "$columnId = ?", whereArgs: [id]);
  }

  Future<int> updateItem(NoDoItem item) async
  {
   var dbClient =await database;
   return await dbClient.update(tableName, item.toMap(),
   where: "$columnId=?", whereArgs: [item.id]);
  }

  Future close() async
  {
    var dbClient =await database;
    return dbClient.close();
  }
}

nodo_item.dart

import 'package:flutter/material.dart';


class NoDoItem extends StatelessWidget {
  late String _itemName;
  late String _dateCreated;
  late int _id;

  NoDoItem( this._itemName , this._dateCreated, {Key? key}) : super(key: key);

  NoDoItem.map(dynamic obj, {Key? key}) : super(key: key)
  {
    _itemName = obj['ItemName'];
    _dateCreated = obj['DateCreated'];
    _id = obj['id'];
  }

  String get itemName => _itemName;
  String get dateCreated => _dateCreated;
  int get id => _id;

  Map<String , dynamic>toMap()
  {
    var map = <String , dynamic>{};
    map['ItemName'] = _itemName;
    map['DateCreated'] = _dateCreated;
    /*if(_id !=null)
      {
        map['id'] = _id;
      }*/
    map['id'] = _id;
    return map;
  }

  NoDoItem.fromMap(Map<String , dynamic>map, {Key? key}) : super(key: key)
  {
    _itemName = map['ItemName'];
    _dateCreated = map['DateCreated'];
    _id = map['id'];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(_itemName ,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 16.5,
            fontWeight: FontWeight.bold
          ),),
          Container(
            margin: const EdgeInsets.only(top: 5.0),
            child:  Text('Created on: $_dateCreated',
              style: const TextStyle(
                color: Colors.white70,
                fontStyle: FontStyle.italic,
                fontSize: 13.4
              ),),
          )
        ],
      )
    );
  }
}

notodo_screen.dart

import 'package:flutter/material.dart';
import 'package:no_to_do_app/model/nodo_item.dart';
import 'package:no_to_do_app/util/database_client.dart';

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

  @override
  _NoToDoScreenState createState() => _NoToDoScreenState();
}

class _NoToDoScreenState extends State<NoToDoScreen> {
  final TextEditingController _textEditingController = TextEditingController();
  var db = DatabaseHelper();

  void _hndleSubmitted(String text) async
  {
    _textEditingController.clear();
    NoDoItem noDoItem = NoDoItem(text,DateTime.now().toIso8601String());
    int savedItemId = await db.saveItem(noDoItem);

    debugPrint("Item saved ID: $savedItemId");
  }

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      backgroundColor: Colors.black87,
      body:  Column(),
      floatingActionButton:  FloatingActionButton(
          tooltip: 'Add Item',
          backgroundColor: Colors.redAccent,
          child:  const ListTile(
              title:  Icon(Icons.add)
          ),
          onPressed: _showFormDialog),

    );

  }

  void _showFormDialog() {
    var alert = AlertDialog(
      content: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _textEditingController,
              autofocus: true,
              decoration: const InputDecoration(
                labelText: 'item',
                hintText: "eg. Don't buy Stuff",
                icon: Icon(Icons.add_circle_outline_outlined)
              ),
            ))
        ],
      ),
          actions:[
            TextButton(
              style: ButtonStyle(
        foregroundColor: MaterialStateProperty.all<Color>(Colors.blue),
    ),
    onPressed: ()
    {
    _hndleSubmitted(_textEditingController.text);
    _textEditingController.clear();
    },
    child: const Text("Save"),
            ),

            TextButton(
              style: ButtonStyle(
            foregroundColor: MaterialStateProperty.all<Color>(Colors.blue),
            ),
            onPressed:() => Navigator.pop(context),
            child: const Text("Cancel"),)
          ]
    );
    showDialog(context: context,
    builder:(_)
    {
      return alert;
    });
  }
}

Compiler Showing Errors

E/flutter ( 3777): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: LateInitializationError: Field '_id@21016470' has not been initialized.
E/flutter ( 3777): #0      NoDoItem._id (package:no_to_do_app/model/nodo_item.dart)
E/flutter ( 3777): #1      NoDoItem.toMap (package:no_to_do_app/model/nodo_item.dart:31:17)
E/flutter ( 3777): #2      DatabaseHelper.saveItem (package:no_to_do_app/util/database_client.dart:54:53)
E/flutter ( 3777): <asynchronous suspension>
E/flutter ( 3777): #3      _NoToDoScreenState._hndleSubmitted (package:no_to_do_app/ui/notodo_screen.dart:20:23)
E/flutter ( 3777): <asynchronous suspension>
E/flutter ( 3777): 

CodePudding user response:

Late value need initial value and you need initialization it. Your code have not this. Try this:

late String param = '';
late int paramId = 0;

CodePudding user response:

ok i have fixed this issue i was not initializing the late fields in my code was using then without initialization

late String _itemName;
late String _dateCreated;
late int _itemId;

right method is

late String _itemName = "";
late String _dateCreated = "";

and itemId is the primary key it should not be initialized because database will put the value in it automatically for us because it is primary key we should make it nullable by placing ? i.e

  int? _itemId; 
  • Related