Flutter中使用已存在的sqlite数据库

  1. 将数据库文件放入/根目录/assets/ 文件夹.

  2. 打开pubspec.ymal文件,在flutter里加入:

    Flutter中使用已存在的sqlite数据库_第1张图片
    image.png

  3. 打开数据库的代码:

    var databasesPath = await getDatabasesPath();
    var path = join(databasesPath, "demo_asset_example.db");
    
    // Check if the database exists
    var exists = await databaseExists(path);
    
    if (!exists) {
      // Should happen only the first time you launch your application
      print("Creating new copy from asset");
    
      // Make sure the parent directory exists
      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (_) {}
        
      // Copy from asset
      ByteData data = await rootBundle.load(join("assets", "example.db"));
      List bytes =
      data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      
      // Write and flush the bytes written
      await File(path).writeAsBytes(bytes, flush: true);
    
    } else {
      print("Opening existing database");
    }
    // open the database
    db = await openDatabase(path, readOnly: true);
    
  4. 显示查询结果,可以使用FutureBuilder:

      child: FutureBuilder(
         future: DBProvider.db.getOne(ran),
         builder: (BuildContext context, AsyncSnapshot snapshot) {
           if (snapshot.hasData) {
             print("*************");
             print(snapshot.data); //snapshot.data就是查询出来的这条数据
             daan = snapshot.data.daan;
              tigan = snapshot.data.tigan;
              xuanxiang = snapshot.data.xuanxiang;
              xuanxiang = xuanxiang.replaceAll("|", "\n");
               result = tigan + '\n\n' + xuanxiang;
             return Text(result,style:TextStyle(fontSize: 25),);
    
          } else {
             return Center(child: CircularProgressIndicator());
           }
         },
       ),
    

你可能感兴趣的:(Flutter中使用已存在的sqlite数据库)