无法使用Flutter在Dart中写入JSON文件 [英] Unable to write to JSON file in dart using flutter

查看:86
本文介绍了无法使用Flutter在Dart中写入JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够读取JSON文件,但似乎无法写入或更新JSON文件.我可以更新JSON字符串,但似乎无法将JSON字符串写入文件.下面的代码是我用来读取文件的代码.但是,我无法再写入同一文件.

I am able to read a JSON file but I can’t seem to write to or update a JSON file. I’m able to update a JSON string but can’t seem up write my json string to a file. The code below is the what I used to read the file. However, I’m not able to then write to the same file.

new ListTile(

        title: new Text("Close" ),
        trailing: new Icon(Icons.cancel),
        onTap: loadpos,
      )
class NewPage {
  final String title;
  final Color color;
  NewPage({this.title,this.color});
}


Future <String> _loadpos() async{
    return await rootBundle.loadString('assets/button.json');
  }

Future <String> loadpos() async{
  String jsonword = await _loadpos();
//  _parseJsonForPos(jsonword);
  List data = json.decode(jsonword);
 // data[0]["backgrndcolor"] = "black";
  print(data[0]["navbar"]);
}


String _parseJsonForPos(String jsonString) {
  List data = json.decode(jsonString);

  print(data[0]["_value"]);

}

资产文件:(button.json)

Assets file: (button.json)

[{"navbar":"top"}]

[{"navbar" : "top"}]

印刷价值:

Performing hot reload...
Reloaded 5 of 430 libraries in 1,474ms.
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/art     (15546): Background sticky concurrent mark sweep GC freed 222431(11MB) AllocSpace objects, 0(0B) LOS objects, 93% free, 911KB/12MB, paused 553us total 113.423ms
I/art     (15546): Background partial concurrent mark sweep GC freed 222396(11MB) AllocSpace objects, 0(0B) LOS objects, 92% free, 1027KB/13MB, paused 523us total 124.949ms
Lost connection to device.

  • 我当前面临的问题是我无法写入值并将其更新为JSON文件.
  • 为了尝试尝试另一种读取和写入JSON文件的方法,我使用了另一种方法来创建和写入JSON文件,但是我发现它仅临时存储和读取而不写入JSON文件..

    In pursuit of trying another way to read and write to a JSON file, I used another method to create and write to the JSON file but I’ve found that this only temporarily stores and reads and does not write to a JSON file.

    据我在Android上的了解,getApplicationDocumentsDirectory()方法返回AppData目录.但是,当我在手机上的此目录中搜索时,找不到我的button.json文件.

    From what I understand on Android, the getApplicationDocumentsDirectory() method returns the AppData directory. However, when I searched within this directory on my phone, I could not find my button.json file.

    import 'package:flutter/material.dart';
    import 'dart:io';
    import 'dart:convert';
    import 'package:path_provider/path_provider.dart';
    
    void main() {
      runApp(new MaterialApp(
        home: new Home(),
      ));
    }
    
    class Home extends StatefulWidget {
      @override
      State createState() => new HomeState();
    }
    
    class HomeState extends State<Home> {
    
      TextEditingController keyInputController = new TextEditingController();
      TextEditingController valueInputController = new TextEditingController();
    
      File jsonFile;
      Directory dir;
      String fileName = "button.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() {
        keyInputController.dispose();
        valueInputController.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 key, dynamic value) {
        print("Writing to file!");
        Map<String, dynamic> content = {key: value};
        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 new Scaffold(
          appBar: new AppBar(title: new Text("JSON Tutorial"),),
          body: new Column(
            children: <Widget>[
              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: keyInputController,
              ),
              new TextField(
                controller: valueInputController,
              ),
              new Padding(padding: new EdgeInsets.only(top: 20.0)),
              new RaisedButton(
                child: new Text("Add key, value pair"),
                onPressed: () => writeToFile(keyInputController.text, valueInputController.text),
              )
            ],
          ),
        );
      }
    }
    

    TL; DR:我可以创建一个json字符串,但无法将其写入json文件

    TL;DR: I’m able to create a json string but unable to write it to a json file

    推荐答案

    创建的json文件不可访问的原因是因为使用了 getApplicationDocumentsDirectory().路径为"/data/user/0/{PACKAGE_NAME}/app_flutter",我认为无法使用设备的文件浏览器访问它.

    The reason why the json file created is inaccessible is because getApplicationDocumentsDirectory() was used. Path for this is '/data/user/0/{PACKAGE_NAME}/app_flutter' and I don't think it's accessible using the device's file browser.

    我建议使用 getExternalStorageDirectory(),因为它会将文件写入'/storage/emulated/0/Android/data/{PACKAGE_NAME}/files'并且易于访问.

    I suggest using getExternalStorageDirectory() as it writes files on '/storage/emulated/0/Android/data/{PACKAGE_NAME}/files' and is easily accessible.

    以下是运行您提供的repro的一些屏幕截图.

    Here's some screenshots from running the repro you've provided.

    可以使用文件浏览器访问Json文件

    Json file is accessible using a file browser

    打开json文件会显示文件中写入的相同字符串

    Opening the json file displays the same Strings written in the file

    这篇关于无法使用Flutter在Dart中写入JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆