簡體   English   中英

"<i>How can I update\/add new information to my local JSOn file in Flutter?<\/i>如何在 Flutter 中更新\/添加新信息到我的本地 JSOn 文件?<\/b> <i>(without creating any classes)<\/i> (不創建任何類)<\/b>"

[英]How can I update/add new information to my local JSOn file in Flutter? (without creating any classes)

我做了一個小應用程序,有點像圖書館應用程序,你可以在其中添加你讀過的書。 所以,我有一個本地 JSON 文件,如下所示:

[
  {
    "name": "Harry Potter and the Deathly Hallows",
    "author": "J.K. Rowling",
    "rating": "4.5",
    "category": "Fantasy",
    "url": "some url"
  },
  {
    "name": "For Whom The Bell Tolls",
    "author": "E. Hemingway",
    "rating": "4",
    "category": "Novel",
    "url": "some url#2"
  }
]

在我的 main.dart 文件中,我有一個函數可以讀取我的 JSON 文件,將其解碼並加載到名為“data”的列表中:

readData(){
    DefaultAssetBundle.of(context).loadString("json/books.json").then((s){
      setState(() {
        data = json.decode(s);
      });

    });
  }

@override
  void initState() {
    super.initState();
    readData();

  }

我可以輕松地將新書添加到“數據”中,除了一件事之外,一切都很好,-我不知道如何將信息更新/寫入 JSON,因此應用程序可以在重新啟動后向我顯示新書的更新列表. 我已經添加。 我該怎么做呢? 我應該在 JSON 文件中寫入什么 - 包含所有書籍的更新列表或只是帶有新書的地圖?

對納爾遜蒂亞戈的回答

此代碼在“類AddingPageState 擴展狀態”中:

Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }
  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/books.json');
  }
  Future<File> writeData(List list) async { // "list" is the updated book-list
    final file = await _localFile;
    String encodedData = jsonEncode(list);
    return file.writeAsString('$encodedData');
  }

我在 onPressed 函數中調用“writeData”。

最好使用本地 NoSql 數據庫(如sembast )進行此操作,這樣您就可以添加、刪除和更新數據。 但是由於您已經在使用 json,您只需要將新更改的data編碼為 json 並再次寫入文件。 要寫入和讀取文件,而不是使用rootBundle讀取此讀取和寫入文件

正如我從您的 JSON 文件中看到的,您將 Books 存儲為 JSON 對象列表,這將使事情變得更容易。

但是您在不添加新類的情況下解決這個問題的請求有點奇怪,因為在您的情況下添加 Book 類會使事情變得更容易。

所以我會給你一個解決方案,假設你創建了一個新的 Book 類。

  1. 首先像您當前所做的那樣閱讀文件。
  2. 將文件內容存儲在動態列表的列表中。
  3. 使用 map 函數遍歷列表,使用 Book 類中的 from JSON 函數添加,將 JSON 解碼為 book 對象,然后在該地圖上應用 toList() 函數。
  4. 將結果返回到您的 UI 並將其視為任何其他列表。
  5. 當您要添加新 Book 時,請創建 book 類的新對象並將其添加到您的列表中。
  6. 當用戶添加完成后,將列表轉換為 JSON 對象 agian 並再次存儲在文件中;

像這樣的東西:

The Book Class:

class Book {
  String? name;
  String? author;
  String? rating;
  String? category;
  String? url;

  Book({
    required this.name,
    required this.author,
   required this.rating,
  required  this.category,
    required this.url,
  });

  Book.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    author = json['author'];
    rating = json['rating'];
    category = json['category'];
    url = json['url'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['author'] = this.author;
    data['rating'] = this.rating;
    data['category'] = this.category;
    data['url'] = this.url;
    return data;
  }
  @override
  String toString() {
    return 'Book(name: $name, author: $author, rating: $rating, category: $category, url: $url)';
  }
}

和主要功能

void main() {
  /// read the file the way you like
  List<dynamic> list = [
    {
      "name": "Harry Potter and the Deathly Hallows",
      "author": "J.K. Rowling",
      "rating": "4.5",
      "category": "Fantasy",
      "url": "some url"
    },
    {
      "name": "For Whom The Bell Tolls",
      "author": "E. Hemingway",
      "rating": "4",
      "category": "Novel",
      "url": "some url#2"
    }
  ];

  List<Book> books = list
      .map(
        (jsonObject) => Book.fromJson(jsonObject),
      )
      .toList();

  print(books);

  Book newBook = Book(
      name: 'Some Book',
      author: 'Some Author',
      rating: 'Some rating',
      category: 'Some category',
      url: 'Some Url');

  books.add(newBook);

  print(books);

  books
      .map(
        (book) => book.toJson(),
      )
      .toList();
  
  //Write the the file again to storage or anywhere else 
}

請參閱以下示例。 但它需要創建一個類。 示例json<\/strong>文件如下所示(與您的 json 文件非常相似) -

[
  {"name":"Ash","age":"22","hobby":"golf"},
  {"name":"philip","age":"17","hobby":"fishing"},
  {"name":"charles","age":"32","hobby":"drawing"},
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM