Search code examples
jsonflutterparsingasynchronoussynchronous

Parse local json file synchronously without future/async


I'm pretty new to Flutter and I'm trying to parse a local json file into a List of objects. Here is my code so far:

import 'dart:convert';
import 'dart:async' show Future;
import 'package:flutter/services.dart';

class ItemManager {
  List<Item> items;

  ItemManager() {
    loadItems();
  }

  void loadItems() async {
    var tempList = await getItems();
    items = tempList;
  }

  Future<List<Item>> getItems() async {
    String dataString = await loadAsset();
    var json = jsonDecode(dataString)['items'] as List;
    List<Item> parsedList = json.map((i) => Item.fromJson(i)).toList();
    return parsedList;
  }

  Future<String> loadAsset() async {
    String value = await rootBundle.loadString('assets/items.json');
    return value;
  }
}

class Item {
  String title = "";
  String subtitle = "";
  int subIcon = 1;
  bool isFavourite = false;
  String html = "";

  Item({this.title, this.subtitle, this.subIcon, this.isFavourite, this.html});

  factory Item.fromJson(Map<String, dynamic> parsedJson) {
    return Item(
      title:  parsedJson['title'].toString(),
      subtitle:  parsedJson['subtitle'].toString(),
      subIcon: parsedJson['subIcon'],
      isFavourite:  parsedJson['isFavourite'],
      html:  parsedJson['html'],
    );
  }
}

I only saw people parsing json with async functions, but that's just not how I want it to be. Can anyone explain how I can parse a json synchronously, so my List<Item> items already will have all items right after the loadItems() method? Any ideas?


Solution

  • So, if anybody got the same question as me, I decided to try the first method that is mentioned in this page: Load JSON data using Flutter in different ways

    I got the problem that my main function got "zoned". Then I found out about this question: Flutter - Android app shows just a blank screen

    I edited the method 1, instead of void, I used Future<void> main async and simply added WidgetsFlutterBinding.ensureInitialized(); before the await command/line.

    Now the json file gets loaded into a list before the app starts. Note that this pauses the app till the list is loaded! So don't try to load a huge json file.