gpt4 book ai didi

json - 无法使用Flutter在Dart中写入JSON文件

转载 作者:行者123 更新时间:2023-12-03 04:04:22 25 4
gpt4 key购买 nike

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

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"]);

}

Assets 文件:(button.json)

[{“navbar”:“top”}]

打印值(value):
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文件。

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

    最佳答案

    无法访问创建的json文件的原因是因为使用了getApplicationDocumentsDirectory()。路径为“/ data / user / 0 / {PACKAGE_NAME} / app_flutter”,我认为无法使用设备的文件浏览器进行访问。
    我建议使用getExternalStorageDirectory(),因为它会将文件写入“/ storage / emulated / 0 / Android / data / {PACKAGE_NAME} / files”中并且易于访问。
    这是运行您提供的repro的一些屏幕截图。

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

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

    关于json - 无法使用Flutter在Dart中写入JSON文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51604947/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com