You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter(Dart)如何更新本地JSON文件中的指定数据?

Flutter实现本地JSON文件数据修改方案

注意:放置在assets目录下的文件是应用安装包内置的只读资源,无法直接修改。我们需要首次加载时将assets中的JSON文件复制到应用的可读写私有目录,后续所有读写操作都操作该目录下的文件即可实现修改。


1. 配置依赖与资源

在pubspec.yaml中添加依赖和资源声明:

dependencies:
  flutter:
    sdk: flutter
  path_provider: ^2.1.0 # 用于获取应用可读写目录

# 声明assets资源
flutter:
  assets:
    - user_data/UserData.json

2. 完善User模型

新增copyWith方法方便修改不可变字段:

class User {
  final String name;
  final String companyName;
  final String designation;
  final String isAdmin;

  User({
    required this.name,
    required this.companyName,
    required this.designation,
    required this.isAdmin,
  });

  // 新增copyWith方法
  User copyWith({
    String? name,
    String? companyName,
    String? designation,
    String? isAdmin,
  }) {
    return User(
      name: name ?? this.name,
      companyName: companyName ?? this.companyName,
      designation: designation ?? this.designation,
      isAdmin: isAdmin ?? this.isAdmin,
    );
  }

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'] as String,
      companyName: json['companyName'] as String,
      designation: json['designation'] as String,
      isAdmin: json['isAdmin'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    return <String, dynamic>{
      'name': name,
      'companyName': companyName,
      'designation': designation,
      'isAdmin': isAdmin,
    };
  }
}

3. 完整的JSON读写逻辑代码

import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'user_model.dart';

// 获取可读写目录下的JSON文件对象
Future<File> getLocalJsonFile() async {
  final dir = await getApplicationDocumentsDirectory();
  return File('${dir.path}/UserData.json');
}

// 首次启动将assets中的JSON复制到可读写目录
Future<void> copyAssetToLocalDir() async {
  final file = await getLocalJsonFile();
  if (await file.exists()) return; // 已经复制过就跳过
  String assetContent = await rootBundle.loadString('user_data/UserData.json');
  await file.writeAsString(assetContent);
}

// 更新JSON文件中第一个用户的companyName
Future<void> updateJson() async {
  // 先确保文件已经复制到可读写目录
  await copyAssetToLocalDir();
  final file = await getLocalJsonFile();
  
  // 读取文件内容并解析
  String jsonContent = await file.readAsString();
  List<dynamic> rawList = json.decode(jsonContent);
  List<User> userList = rawList.map((e) => User.fromJson(e)).toList();

  // 修改第一个用户的companyName
  userList[0] = userList[0].copyWith(companyName: "NewCompany");

  // 序列化后写入文件
  List<Map<String, dynamic>> updatedJsonList = userList.map((e) => e.toJson()).toList();
  await file.writeAsString(json.encode(updatedJsonList));
}

4. 按钮调用示例

ElevatedButton(
  onPressed: () async {
    await updateJson();
    // 修改完成后可重新读取文件验证内容
  },
  child: const Text("修改第一个用户的公司名称"),
)

内容的提问来源于stack exchange,提问作者Rohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:15:00