【问题标题】:Flutter - How to write String into json filesFlutter - 如何将字符串写入 json 文件
【发布时间】:2022-01-21 11:37:59
【问题描述】:

我遵循了颤振文档中的指南,但不明白它是如何工作的。

我有一个包含用户信息的现有文件,我希望能够写入/更新该文件。

这是我的代码的相关部分:

Future<bool> sendMessage(String sender, String target, String body) async {
    String tempAccountData = await loadMessage();
    List<Map<String, dynamic>> accountData =
        List<Map<String, dynamic>>.from(jsonDecode(tempAccountData));
    //find valid target
    print(accountData);
    print(target);
    for (Map<String, dynamic> accountInfo in accountData) {
      if (accountInfo["username"] == target) {
        //write message
        accountInfo["messages"]
            .add({"time": DateTime.now(), "sender": sender, "message": body});
        writeMessage(accountData);
        return true;
      }
    }
    return false;
  }

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

    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    print(path);
    return File('$path/accountInfo.json');
  }

  Future<File> writeMessage(List<Map<String, dynamic>> accountData) async {
    File file = await _localFile;

    // Write the file
    return file.writeAsString('$accountData');
  }

我不知道路径是什么,我将文件放入 assets/data 中,如下面的屏幕截图所示:(我正在尝试从 accountInfo.dart 读取/写入 accountInfo.json)

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    在运行时无法修改资产中的文件。

    您可以做的是将 Json 中的所有数据写入设备目录之一中的文件,然后在需要时修改该文件或使用数据库来存储所有数据。

    【讨论】:

      【解决方案2】:

      需要执行几个步骤以及您需要了解的事项。首先,资产是不可变的。这意味着您可以读取它们,但不能写入它们。您需要的是一个本地文件。存在于安装应用程序的设备的文件系统上的文件。该文件可以修改,并允许写入。

      流程如下:

      1. 检查是否已有本地文件
      2. 如果没有,请创建它并将初始资产文件的内容放入其中。
      3. 现在可变本地文件已经存在,从它读取和写入。

      这是一个处理该问题的类的代码示例:

      import 'dart:io';
      
      import 'package:flutter/services.dart';
      import 'package:path_provider/path_provider.dart';
      
      const initialAssetFile = 'assets/initial.json';
      const localFilename = 'data.json';
      
      class Repository {
        /// Initially check if there is already a local file.
        /// If not, create one with the contents of the initial json in assets
        Future<File> _initializeFile() async {
          final localDirectory = await getApplicationDocumentsDirectory();
          final file = File('$localDirectory/$localFilename');
      
          if (!await file.exists()) {
            // read the file from assets first and create the local file with its contents
            final initialContent = await rootBundle.loadString(initialAssetFile);
            await file.create();
            await file.writeAsString(initialContent);
          }
      
          return file;
        }
      
        Future<String> readFile() async {
          final file = await _initializeFile();
          return await file.readAsString();
        }
      
        Future<void> writeToFile(String data) async {
          final file = await _initializeFile();
          await file.writeAsString(data);
        }
      }
      

      它基本上会在每次读取或写入之前检查本地文件是否已经创建,如果没有,它会处理。

      请注意,这里没有发生 JSON 特定的事情,这只是默认文件 IO。 JSON 编码/解码应该发生在此之前/之后。

      您只需将初始文件添加到 assets/ 文件夹并在您的 pubspec.yaml 中指定,如下所示:

      flutter:
        assets:
          - assets/initial.json # the file containing the initial data
      #   - assets/ # you can also just add the whole directory
      
      

      完成后,您应该可以使用此 Repository 类中的 readFile()writeFile(String data)

      (确保已调用 WidgetsFlutterBinding.ensureInitialized(); 以与本地文件系统交互可能很重要)

      【讨论】:

      • 所以如果它在 pubspec.yaml 中,该文件可以通过 android 目录访问吗?假设我需要的文件在 assets/data/accountinfo.json 中,我只是指定它,我就可以用路径调用它
      • 如果你将它添加到 pubspec.yaml 中,该文件将可以通过代码示例中的rootBundle 访问,而不是具体的 android 目录。 'path thing' (dart:io) 将允许您读取和写入本地文件,但应用程序需要先创建它。这里要知道的重要一点是资产文件(只读且随应用的 APK 提供)和本地文件(读/写,需要先创建,如 'await file.create() 的代码示例中所示)之间的区别')
      • 谢谢,不过我里面已经有一些数据了,必须手动创建,请问有没有在vscode里面创建文件?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 2020-07-26
      相关资源
      最近更新 更多