Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 在Flatter中,将带有图像的对象本地存储在磁盘上的最佳方法?_Flutter_Sharedpreferences_Data Persistence - Fatal编程技术网

Flutter 在Flatter中,将带有图像的对象本地存储在磁盘上的最佳方法?

Flutter 在Flatter中,将带有图像的对象本地存储在磁盘上的最佳方法?,flutter,sharedpreferences,data-persistence,Flutter,Sharedpreferences,Data Persistence,我正在为一个人制作一个超级简单的烹饪书(就像字面上的食物)应用程序,所以我没有想过我想要/需要使用数据库或任何互联网连接。当用户创建配方时,配方对象包含一组字符串和一个图像,如下所示: class Recipe { String _title; Image _picture; Uint8List _imageBytes; int _prepTime; int _cookTime; int _totalTime; String _description; List&l

我正在为一个人制作一个超级简单的烹饪书(就像字面上的食物)应用程序,所以我没有想过我想要/需要使用数据库或任何互联网连接。当用户创建配方时,配方对象包含一组字符串和一个图像,如下所示:

class Recipe {
 String _title;
  Image _picture;
  Uint8List _imageBytes;
  int _prepTime;
  int _cookTime;
  int _totalTime;
  String _description;
  List<String> _ingredientList;
  List<String> _directionsList;


....
}


类配方{
字符串标题;
图片;
Uint8List_imageBytes;
国际时间;
国际烹饪时间;
总时间;
字符串描述;
列表_ingredientList;
列表_方向列表;
....
}
用户可能会创建大约20个食谱。不需要任何个人资料,因为我只是为一个人制作应用程序。配方是唯一需要保存的应用程序数据


到目前为止,我已经尝试将每个菜谱编码为JSON,然后将其保存到共享的_首选项中(请注意我尝试用于此目的的_imageBytes字段)。但这不仅看起来是一种非常低效的做事方式,我甚至还没能让它发挥作用。似乎很难获得这方面的信息:在不使用数据库的情况下,人们通常如何将这些信息本地存储在颤振应用程序中?或者说数据库就是解决这个问题的方法吗?

您需要路径提供程序包和Flatter缓存管理器

import 'dart:async';
import 'dart:io' as Io;
import 'package:image/image.dart';

import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path_provider/path_provider.dart';
class SaveFile {

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }
  Future<Io.File> getImageFromNetwork(String url) async {

    var cacheManager = await CacheManager.getInstance();
    Io.File file = await cacheManager.getFile(url);
    return file;
  }

  Future<Io.File> saveImage(String url) async {

    final file = await getImageFromNetwork(url);
    //retrieve local path for device
    var path = await _localPath;
    Image image = decodeImage(file.readAsBytesSync());

    Image thumbnail = copyResize(image, 120);

    // Save the thumbnail as a PNG.
    return new Io.File('$path/${DateTime.now().toUtc().toIso8601String()}.png')
      ..writeAsBytesSync(encodePng(thumbnail));
  }
}
下面的示例演示如何使用缓存管理器存储网络映像

import 'dart:async';
import 'dart:io' as Io;
import 'package:image/image.dart';

import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path_provider/path_provider.dart';
class SaveFile {

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }
  Future<Io.File> getImageFromNetwork(String url) async {

    var cacheManager = await CacheManager.getInstance();
    Io.File file = await cacheManager.getFile(url);
    return file;
  }

  Future<Io.File> saveImage(String url) async {

    final file = await getImageFromNetwork(url);
    //retrieve local path for device
    var path = await _localPath;
    Image image = decodeImage(file.readAsBytesSync());

    Image thumbnail = copyResize(image, 120);

    // Save the thumbnail as a PNG.
    return new Io.File('$path/${DateTime.now().toUtc().toIso8601String()}.png')
      ..writeAsBytesSync(encodePng(thumbnail));
  }
}
导入'dart:async';
导入“dart:io”作为io;
导入“package:image/image.dart”;
导入“包:flatter_cache_manager/flatter_cache_manager.dart”;
导入“package:path_provider/path_provider.dart”;
类保存文件{
未来获取\u本地路径异步{
最终目录=等待getApplicationDocumentsDirectory();
返回directory.path;
}
未来getImageFromNetwork(字符串url)异步{
var cacheManager=wait cacheManager.getInstance();
Io.File File=wait cacheManager.getFile(url);
返回文件;
}
将来的saveImage(字符串url)异步{
最终文件=等待getImageFromNetwork(url);
//检索设备的本地路径
var path=await\u localPath;
Image=decodeImage(file.readAsBytesSync());
图像缩略图=复制调整大小(图像,120);
//将缩略图另存为PNG。
返回新的Io.File(“$path/${DateTime.now().toUtc().toIso8601String()}.png”)
..writeAsBytesSync(encodePng(缩略图));
}
}

使用本地数据库(如
SQLite
)在颤振中高效地保存数据是一种可行的方法:

  • 导入正确的依赖项:
  • 打开数据库:

  • 我如何命名URL重要吗?
    WidgetsFlutterBinding.ensureInitialized();
    // Open the database and store the reference.
    final Future<Database> database = openDatabase(
      join(await getDatabasesPath(), 'recipes_database.db'),
    );
    
    final Future<Database> database = openDatabase(
      join(await getDatabasesPath(), 'doggie_database.db'),
      onCreate: (db, version) {
        return db.execute(
          "CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TITLE)", // all the properties here
        );
      },
      version: 1,
    );
    
    Future<void> inserRecipe(Recipe recipe) async {
      final Database db = await database;
      await db.insert(
        'recipe',
        recipe.toMap(),
        conflictAlgorithm: ConflictAlgorithm.replace,
      );
    }
    Future<List<Recipe>> recipes() async {
      final Database db = await database;
    
      final List<Map<String, dynamic>> maps = await db.query('recipes');
    
      return List.generate(maps.length, (i) {
        return Recipe(
          title: maps[i]['title'],
          // ... all the properties here
        );
      });
    }
    
    var image = await DefaultCacheManager().getSingleFile(recipe.picture);