如何在不更改 flutter 键的情况下将具有不同值的新映射写入 json 文件?

How to write new map with different values into json file without changing key in flutter?

我正在尝试将新内容作为地图添加到 json 中。它应该看起来像这样:-

[
    {
        "title":"mon",
        "date":"2/3/2020"
    },
    {
        "title":"tue",
        "date":"3/3/2020"
    },
    {
        "title":"wed",
        "date":"4/3/2020"
    }
]

我想在 listview 中展示它。这是我用来创建、编写和显示的代码:-

//new class

class WorkersLog extends StatefulWidget {
  @override
  _WorkersLogState createState() => _WorkersLogState();
}

class _WorkersLogState extends State<WorkersLog> {
  @override
  Widget build(BuildContext context) {
    void _showSettingsPanel() {
      showModalBottomSheet(
          isScrollControlled: true,
          context: context,
          builder: (context) {
            return Container(
              height: MediaQuery.of(context).size.height * .90,
              padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 40.0),
              child: Center(child: WorkerCardData()),
            );
          });
    }

    return Container(
      child: Column(
        children: [
          SizedBox(height: 40),
          Padding(
            padding: EdgeInsets.all(20.0),
            child: Center(
              child: Text(
                  "add document to store wages, loans etc of workers save paper,don't lose track of your accounts!"),
            ),
          ),
          Row(
            children: <Widget>[
              Center(
                child: Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.fromLTRB(150, 350, 0, 5),
                      child: FloatingActionButton.extended(
                        label: Text('add document'),
                        icon: Icon(Icons.save),
                        backgroundColor: Colors.greenAccent,
                        elevation: 5.0,
                        onPressed: () {
                          print('object');
                          _showSettingsPanel();
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

//Create and write file to json

class WorkerCardData extends StatefulWidget {
  @override
  _WorkerCardDataState createState() => _WorkerCardDataState();
}

class _WorkerCardDataState extends State<WorkerCardData> {
  TextEditingController title = new TextEditingController();

  File jsonFile;
  Directory dir;
  String fileName = 'myFile.json';
  bool fileExists = false;
  Map<String, dynamic> fileContent;

  @override
  void initState() {
    super.initState();
    getApplicationDocumentsDirectory().then((Directory directory) {
      dir = directory;
      jsonFile = new File(dir.path + '/' + fileName);
      fileExists = jsonFile.existsSync();
      if (fileExists)
        this.setState(
            () => fileContent = json.decode(jsonFile.readAsStringSync()));
    });
  }

  @override
  void dispose() {
    title.dispose();
    super.dispose();
  }

  void createFile(
      Map<String, dynamic> content, Directory dir, String fileName) {
    print("Creating file!");
    File file = new File(dir.path + "/" + fileName);
    file.createSync();
    fileExists = true;
    file.writeAsStringSync(json.encode(content));
  }

  void writeToFile(String title, dynamic date) {
    print("Writing to file!");
    Map<String, dynamic> content = {'title': title, 'date': date};
    if (fileExists) {
      print("File exists");
      Map<String, dynamic> jsonFileContent =
          json.decode(jsonFile.readAsStringSync());
      jsonFileContent.addAll(content);
      jsonFile.writeAsStringSync(json.encode(jsonFileContent));
    } else {
      print("File does not exist!");
      createFile(content, dir, fileName);
    }
    this.setState(() => fileContent = json.decode(jsonFile.readAsStringSync()));
    print(fileContent);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          new Padding(padding: new EdgeInsets.only(top: 10.0)),
          new Text(
            "File content: ",
            style: new TextStyle(fontWeight: FontWeight.bold),
          ),
          new Text(fileContent.toString()),
          new Padding(padding: new EdgeInsets.only(top: 10.0)),
          new Text("Add to JSON file: "),
          new TextField(
            controller: title,
            decoration: textInputDecoration.copyWith(
                hintText: 'title',
                prefixIcon: Icon(Icons.info, color: Colors.white)),
          ),
          new Padding(padding: new EdgeInsets.only(top: 20.0)),
          new RaisedButton(
            child: new Text("save new document"),
            onPressed: () => writeToFile(title.text, DateTime.now().toString()),
          )
        ],
      ),
    );
  }
}

//display json as list view

class WorkerCard extends StatefulWidget {
  final String title;
  WorkerCard({this.title});
  @override
  _WorkerCardState createState() => _WorkerCardState();
}

Directory dir;
Map<String, dynamic> workerFileContent;
File workerFile;

class _WorkerCardState extends State<WorkerCard> {
  @override
  void initState() {
    super.initState();
    getApplicationDocumentsDirectory().then((Directory directory) {
      dir = directory;
      workerFile = File(dir.path + 'myFile.json');
      workerFileContent = json.decode(workerFile.readAsStringSync());
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (context, index) {
        return Card(
          child: Column(
            children: [
              Text(workerFileContent['title'].toString()),
              Text(workerFileContent['date'].toString()),
            ],
          ),
        );
      },
    );
  }
}

这是我的问题。每次我添加新标题时,文件都会被覆盖。如何在不覆盖之前添加的内容的情况下向我的 json 文件添加新地图?

loganrussell48 Thanks for guiding me to the answer

变化:-

Map<String, dynamic> fileContent;

收件人:-

List fileContent;