简体   繁体   中英

Get datas from local json file in Flutter

I am modifying a repository I found on github and as you seen in code below the app uses API but it is inside the dart file. I copied that json data to ' questions.json ' file, now I want to do something like that (which is wrong of course): var json = 'assets/questions.json';

Any help?

  @override
  Future<bool> getQuestions(
      {StreamedList<Question> questions,
      int number,
      Category category,
      QuestionDifficulty difficulty,
      QuestionType type}) async {

    const json = "{\"response_code\":0......here is the json data........}";

    final jsonResponse = convert.jsonDecode(json);

    final result = (jsonResponse['results'] as List).map((question) => QuestionModel.fromJson(question));

    questions.value = result.map((question) => Question.fromQuestionModel(question)).toList();

    return true;
  }

If you want to load your data from your assets folder, you need 2 things:

1) Make sure that file is included in your pubspec.yaml - refer to the yaml file's comment on how to do that.

2) Use the rootBundle . Something along the lines of:

import 'package:flutter/services.dart';

// code
var data = await rootBundle.loadString('assets/data.json');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM