1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Flutter SQLite connection trouble (for Android)

Discussão em 'Mobile' iniciado por Stack, Outubro 17, 2024 às 12:13.

  1. Stack

    Stack Membro Participativo

    Doing app for Android.(new on flutter) Trying to connect to already existing SQLite file to project. I have issue with connection, it doesnt connecting to file but init empty new one with same name in drirectory of android (Android/data/com.exemple.android_studio_project). In enternet i have seen only lazy initialization variant. There was some methods to locate file, but for some reason they dont working.

    I tried to ask AI but answer wasnt satisfy me.

    **True db location is: D:\android_studio_project\lib\souece.db **

    part of the code sqLite_connect.dart:

    import 'dart:typed_data';

    import 'package:flutter/services.dart';
    import 'package:path_provider/path_provider.dart';
    import 'package:sqflite/sqflite.dart';
    import 'package:path/path.dart';
    import 'dart:io';

    class SqliteConnect {
    static final SqliteConnect instance = SqliteConnect._init();

    SqliteConnect._init();

    Database? _database;

    Future<Database> get database async {
    if (_database != null) return _database!;


    _database = await _initDB('source.db');
    return _database!;
    }

    Future<Database> _initDB(String filePath) async {

    Directory documentsDirectory = await getApplicationDocumentsDirectory();


    String path = join(documentsDirectory.path, filePath);


    bool dbExists = await _checkDbExists(path);


    if (!dbExists) {
    await _copyDbFromAssets(path);
    }


    return await openDatabase(path);
    }


    Future<bool> _checkDbExists(String path) async {
    try {
    return await File(path).exists();
    } catch (e) {
    return false;
    }
    }


    Future<void> _copyDbFromAssets(String path) async {

    ByteData data = await rootBundle.load('android_studio_project/assets/source.db');


    List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);


    await File(path).writeAsBytes(bytes, flush: true);
    }






    }


    I expexting to take data from the file that be in the app

    If theer is technology of storing data in sqlite on Flutter app that i dont know, i will be glad to take advise.

    Continue reading...

Compartilhe esta Página