首页 > 解决方案 > 在 Flutter 中无法将图像保存到设备中?

问题描述

我正在尝试使用 sqllite 在本地设备中保存图像。我正在使用 edge_detection 库来获取裁剪的图像路径并尝试将其保存到设备中。这是我的桌子:

class DBHelper {
  static Future<Database> database() async {
    final dbPath = await sql.getDatabasesPath();
    return sql.openDatabase(path.join(dbPath, 'locations.db'),
        onCreate: (db, version)  => _createDb(db), version: 1);}
  static void _createDb(Database db) {
    db.execute('CREATE TABLE location(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, image TEXT)');
    db.execute('CREATE TABLE images(id INTEGER PRIMARY KEY AUTOINCREMENT, Image TEXT, fileId INTEGER)');
  }

我的插入代码是:

void addImage(int file_id, File pic) {
    final newpicture = Picture(file_id: file_id, image: pic);
    _items.add(newpicture);
    notifyListeners();
    DBHelper.insert('images', {
      'Image': newpicture.image.path,
      'fileId': newpicture.file_id,
    });
  }

我正在使用以下代码获取数据:

Future<void> fetchAndSetPlaces() async {
    final dataList = await DBHelper.getData('images');
    print(dataList);
    _items = dataList
        .map(
          (item) => Picture(
            image:File(item['Image']),
            file_id: item['fileId'],
          ),
        )
        .toList();
    notifyListeners();
  }
}

我的模型是这样的:

class Picture{
  int? id;

  final int file_id;
  final File image;

  Picture({required this.file_id,required this.image});



}

这就是我使用该函数获取图像路径的方式:

Future<void> getImage(int? file_id) async {
    String? imagePath;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      imagePath = (await EdgeDetection.detectEdge);
      print("$imagePath");
    } on PlatformException {
      imagePath = 'Failed to get cropped image path.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    var directory = await getApplicationDocumentsDirectory();
    String path=directory.path;



    setState(() {
      _imagePath = imagePath;
    });
    print(_imagePath);

    Provider.of<Images>(context, listen: false)
        .addImage(file_id!, File(_imagePath!));
  }

这就是我在小部件中获取数据的方式:

Consumer<Images>(
                  builder: (ctx, titles, ch) => GridView.builder(
                      itemCount: titles.items.length,
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        mainAxisSpacing: 2,
                        crossAxisSpacing: 2,
                      ),
                      itemBuilder: (ctx, index) {
                        return Column(
                          children: <Widget>[
                            Expanded(
                              child: Container(
                                padding:EdgeInsets.symmetric(vertical: 10,horizontal:10),
                                  child: Image.file(titles.items[index].image)),

这是在添加图片之后: 这是添加图片后 这是在关闭并重新打开应用程序之后: 在此处输入图像描述

问题是我拍完照片后可以看到照片,但是当我关闭应用程序然后再次重新打开时,没有图片可以显示。我该如何解决这个问题?提前谢谢。

更新:所以当我在发布模式下运行我的代码时没有问题。我认为调试模式是问题所在。

标签: fluttersqfliteflutter-iosflutter-image

解决方案


第一步将数据库中图像的数据类型更改为 BLOB db.execute('CREATE TABLE images(id INTEGER PRIMARY KEY AUTOINCREMENT, Image BLOB, fileId INTEGER)');

第二步将模型中的数据类型更改为 Uint8List

最终的 Uint8List 图像;

最后,当您读取图像时,将其读取为 Uint8List


推荐阅读