readJsonFromFile static method

Future<Map<String, dynamic>?> readJsonFromFile(
  1. String filePath, {
  2. bool fromAsset = false,
})

从文件中读取 JSON 数据并解析为 Map

filePath JSON 文件路径 fromAsset 是否从 Assets 中读取(默认false,即从沙盒文件读取)

返回值: Future<Map<String, dynamic>?> 成功返回 JSON 对象,失败或文件不存在返回 null

使用示例:

// 从沙盒文件读取
final data = await JsonUtil.readJsonFromFile('/tmp/example.json');
if (data != null) {
  print(data['a']); // 1
}

// 从 Assets 读取
final data = await JsonUtil.readJsonFromFile('assets/data/config.json', fromAsset: true);

Implementation

static Future<Map<String, dynamic>?> readJsonFromFile(
  String filePath, {
  bool fromAsset = false,
}) async {
  try {
    String jsonString;
    if (fromAsset) {
      jsonString = await rootBundle.loadString(filePath);
    } else {
      final file = File(filePath);
      if (!file.existsSync()) {
        return null;
      }
      jsonString = await file.readAsString();
    }
    return jsonDecode(jsonString) as Map<String, dynamic>;
  } catch (e) {
    Logger.log('Error reading JSON from file: $e');
    return null;
  }
}