Laksh Ahir
Laksh Ahir

Reputation: 21

Sqflite package problem while making a simple app for implementing CRUD operation

I'm learning Flutter. I have created an Flutter app (Project) named my_diary_using_sqflite for practicing CRUD operation in SQLite Database.

But I'm stuck among sqflite package and sqflite_common_ffi package and sqflite_common_ffi_web package.

I'm presenting two dart files code here, I think the problem is in those two files.

1. note_repository.dart [ This is the file where I write the code of all CRUD operation function and Database related functions ]

import 'package:my_diary_using_sqflite/Models/note.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class NotesRepository {
  static const _dbName = 'notes_database.db';
  static const _tableName = 'notes';

  static Future<Database> database() async {
    return openDatabase(
      join(await getDatabasesPath(), _dbName),
      onCreate: (db, version) {
        return db.execute(
            'CREATE TABLE $_tableName(id INTEGER PRIMARY KEY, title TEXT, description TEXT, createdAt TEXT)');
      },
      version: 1,
    );
    // return databaseFactoryFfi.openDatabase(_dbName);

    // Directory directory = await getApplicationDocumentsDirectory();
    // String path = directory.path + _dbName;
    // return openDatabase(
    //   path,
    //   onCreate: (db, version) {
    //     return db.execute(
    //         'CREATE TABLE $_tableName(id INTEGER PRIMARY KEY, title TEXT, description TEXT, createdAt TEXT)');
    //   },
    //   version: 1,
    // );
  }

  static insert({required Note note}) async {
    print("Finally entering inserted function");
    final db = await database();
    await db.insert(_tableName, note.toMap());
  }

  static Future<List<Note>> getNotes() async {
    final db = await database();
    final List<Map<String, dynamic>> maps = await db.query(
        _tableName); // You can mention other parameters like columns, where, whereArgs, groupBy, having, orderBy, limit, offset

    return List.generate(maps.length, (i) {
      return Note(
          id: maps[i]['id'] as int,
          title: maps[i]['title'] as String,
          description: maps[i]['description'] as String,
          createdAt: DateTime.parse(maps[i]['createdAt']));
    });
  }
}

When I run the app in Windows (Chrome), and after going the screen of add new note and when I click on submit checkmark icon after filling the form by entering Title and Description, Error is

It is saying that i'm using sqflite_common_ffi, but in fact, I use sqflite

my pubspec.yaml file code

dependencies:
  
  flutter:
    sdk: flutter
    
  cupertino_icons: ^1.0.2
  sqflite: ^2.3.3
  intl: ^0.19.0
  path_provider: ^2.1.3
  sqflite_common_ffi: ^2.3.3
  sqflite_common_ffi_web: ^0.4.3+1

here, extra dependencies were added after the error come into my way one by one..

and after this first Error of sqflite_common_ffi of databaseFactory, I made a change to my 2. main.dart file, that is

import 'package:flutter/material.dart';
import 'package:my_diary_using_sqflite/Screens/home_screen.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  sqfliteFfiInit();
  databaseFactory = databaseFactoryFfi;
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: "My Diary",
        home: Home_Screen());
  }
}

and then I feel that now it will work for me. but again i run the app, and this time only white screen with Error :

Rejecting promise with error: Unsupported operation: Unsupported on the web, use sqflite_common_ffi_web

That's why, I decided to add sqflite_common_ffi_web dependency, But not went out from this errors. The problem may be path related, but direct me what is the actual problem? And How it can be solved. That's why I can perform CRUD operation successfully. :)

Upvotes: 0

Views: 580

Answers (1)

alextk
alextk

Reputation: 6239

Sorry for the poor documentation. On the web you need to follow the steps here: https://pub.dev/packages/sqflite_common_ffi_web#setup

Build the javascript binaries:

dart run sqflite_common_ffi_web:setup

Set the proper database factory upon starts:

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:sqflite_common_ffi_web/sqflite_ffi_web.dart';

Future<void> main() async {
  // Use sqflite on MacOS/iOS/Android.
  WidgetsFlutterBinding.ensureInitialized();
  if (kIsWeb) {
    // Use web implementation on the web.
    databaseFactory = databaseFactoryFfiWeb;
  } else {
    // Use ffi on Linux and Windows.
    if (Platform.isLinux || Platform.isWindows) {
      databaseFactory = databaseFactoryFfi;
      sqfliteFfiInit();
    }
  }
  var db = await openDatabase(inMemoryDatabasePath);
  print((await db.rawQuery('SELECT sqlite_version()')).first.values.first);
  await db.close();
}

Upvotes: 1

Related Questions