【问题标题】:Access SQLite DB in Flutter在 Flutter 中访问 SQLite DB
【发布时间】:2021-03-28 05:48:51
【问题描述】:

我正在使用 SQLite 在我的原生 Android 代码中创建一个数据库。现在我想在 Flutter 中访问同一个数据库,下面是我的代码:

class DatabaseHelper
{
    static final _dbName="abc.db";
    static final _dbVersion=1;
    DatabaseHelper._privateConstructor();
    static final DatabaseHelper instance=DatabaseHelper._privateConstructor();
    static Database _database;
    Future<Database> get datatbase async
    {
        if(_database!=null) {
            print(_database.path);
            return _database;
        }/* */
    }


    Future<List<Map<String,dynamic>>> getAllLogs()async
    {
        final Database db= await instance.datatbase;
        return await db.query("calls_history");
    }

每当我在 Flutter Widget 中调用 getAllLogs 时,都会收到错误消息:calls_history doesn't exist

但是,当我在本机上运行相同的查询时,它会返回结果

【问题讨论】:

    标签: database flutter sqlite sqflite


    【解决方案1】:

    在flutter方面你可以使用sqflite插件,这个插件是建立在原生SQLite之上的,所以你不需要做任何特别的事情,只需在flutter中引用相同的数据库名称即可。

    在我的一个颤振项目中,我使用原生 android 来编写代码来接收消息并将它们保存在 SQLite 数据库中,在颤振方面,我使用相同的数据库使用 sqflite 来显示数据库的内容。 这是颤振侧代码

    import 'dart:async';
    import 'package:path/path.dart';
    import 'package:sqflite/sqflite.dart';
    
    class SMSHelper {
      Database? db;
    
      Future open() async {
        db = await openDatabase(
            //  by default path for database on the device is /data/data/<your app id>/databases/<your database file.db>
            join(await getDatabasesPath(), 'ofs_sms_database.db'),
            version: 1, onCreate: (Database db, int version) async {
          await db.execute(
              "CREATE TABLE smslogs(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, employeeID TEXT, department TEXT, module TEXT, message TEXT, safeUnsafeStatus TEXT, contactNo Text, dateTime INTEGER)");
        });
      }
    
      Future<void> insertSMS(SMSLog smsLog) async {
        await db?.insert(
          'smslogs',
          smsLog.toMap(),
          conflictAlgorithm: ConflictAlgorithm.replace,
        );
      }
    
      Future<List<SMSLog>> getAllSMS() async {
        if (db == null) {
          open();
        }
        final List<Map<String, dynamic>>? maps = await db?.query('smslogs');
    
        // Convert the List<Map<String, dynamic> into a List<Dog>.
        if (maps != null) {
          return List.generate(maps.length, (i) {
            return SMSLog(
                employeeID: maps[i]['employeeID'],
                department: maps[i]['department'],
                module: maps[i]['module'],
                message: maps[i]['message'],
                safeUnsafeStatus: maps[i]['safeUnsafeStatus'],
                contactNo: maps[i]['contactNo'],
                dateTime: maps[i]['dateTime']);
          });
        } else {
          return [];
        }
      }
    
      Future close() async => db?.close();
    }
    
    class SMSLog {
      final String employeeID;
      final String department;
      final String module;
      final String message;
      final String safeUnsafeStatus;
      final String contactNo;
      final int dateTime;
    
      SMSLog(
          {required this.employeeID,
          required this.department,
          required this.module,
          required this.message,
          required this.safeUnsafeStatus,
          required this.contactNo,
          required this.dateTime});
    
      Map<String, dynamic> toMap() {
        return {
          'employeeID': employeeID,
          'department': department,
          'module': module,
          'message': message,
          'safeUnsafeStatus': safeUnsafeStatus,
          'contactNo': contactNo,
          'dateTime': dateTime
        };
      }
    }
    

    【讨论】:

      【解决方案2】:

      要使用 SQLite 数据库,请导入 sqflitepath 包。

      dependencies:
        flutter:
          sdk: flutter
        sqflite:
        path:
      

      确保将包导入您将使用的文件中。

      import 'dart:async';
      
      import 'package:path/path.dart';
      import 'package:sqflite/sqflite.dart';
      

      打开数据库

      1. 使用sqflite 包中的getDatabasesPath() 定义数据库文件的路径,并结合路径包中的连接函数。
      2. 使用来自sqfliteopenDatabase() 函数打开数据库。

      为了使用关键字await,代码必须放在async 函数中。您应该将以下所有表格函数放入void main()async {}

      // Avoid errors caused by flutter upgrade.
      // Importing 'package:flutter/widgets.dart' is required.
      WidgetsFlutterBinding.ensureInitialized();
      // Open the database and store the reference.
      final database = openDatabase(
        // Set the path to the database. Note: Using the `join` function from the
        // `path` package is best practice to ensure the path is correctly
        // constructed for each platform.
        join(await getDatabasesPath(), 'doggie_database.db'),
      );
      

      【讨论】:

        猜你喜欢
        • 2012-02-22
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-01
        • 2012-04-27
        • 2014-09-11
        • 1970-01-01
        相关资源
        最近更新 更多