在本地获取并存储json

时间:2018-07-02 14:55:12

标签: dart flutter

我之前问过问题here,但仍未取得太大进展。我试图从端点获取json格式的列表,并将其分配给实例,然后逐步执行。

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

import '../utils/quiz.dart';
import '../utils/question.dart';

Quiz quiz1 = Quiz([
  Question(
      question: 'What is 1x1',
      option1: '2',
      option2: '3',
      option3: '4',
      option4: '1',
      answer: '1'),
  Question(
      question: 'What is 1x2',
      option1: '2',
      option2: '3',
      option3: '4',
      option4: '1',
      answer: '1'),
  Question(
      question: 'What is 1x3',
      option1: '2',
      option2: '3',
      option3: '4',
      option4: '1',
      answer: '1'),
  Question(
      question: 'What is 1x4',
      option1: '2',
      option2: '3',
      option3: '4',
      option4: '1',
      answer: '1'),
  Question(
      question: 'What is 1x5',
      option1: '5',
      option2: '3',
      option3: '4',
      option4: '1',
      answer: '1')
]);



class QuestionScreen extends StatefulWidget {
  @override
  _QuestionScreenState createState() => new _QuestionScreenState();
}

class _QuestionScreenState extends State<QuestionScreen> {
  Quiz quiz;
  Question currentQuestion;
  String questionText;
  int questionNumber;
  bool isCorrect;
  String option1;
  String option2;
  String option3;
  String option4;
  String answer;
  int index;
  int counter = 0;

  int _selected;
  String url = 'http://www.cloudace.io/questions';

  void onChanged(int value) {
    setState(() {
      _selected = value;
    });
  }


List<Question> parseQuestions(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Question>((json) => Question.fromJson(json)).toList();
}

Future<List<Question>> fetchQuestion(http.Client client) async {
  final response = await client.get('http://www.cloudace.io/questions');

  return parseQuestions(response.body);//return compute(parseQuestions, response.body);
}

Future assignQuiz() async {
    quiz = Quiz(await fetchQuestion(http.Client()));
  }

  @override
  void initState() {
    super.initState();
    assignQuiz();
    print(quiz.toString());
  }

  @override
  Widget build(BuildContext context) {
    if (quiz != null) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Quiz'),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Text(quiz.questions[counter].question),
            RadioListTile(
                value: 0,
                groupValue: _selected,
                onChanged: (int value) {
                  onChanged(value);
                },
                activeColor: Colors.red,
                subtitle: Text(
                  quiz.questions[counter].option1,
                )),
            RadioListTile(
                value: 1,
                groupValue: _selected,
                onChanged: (int value) {
                  onChanged(value);
                },
                activeColor: Colors.red,
                subtitle: Text(
                  quiz.questions[counter].option2,
                )),
            RadioListTile(
                value: 2,
                groupValue: _selected,
                onChanged: (int value) {
                  onChanged(value);
                },
                activeColor: Colors.red,
                subtitle: Text(
                  quiz.questions[counter].option3,
                )),
            RadioListTile(
                value: 3,
                groupValue: _selected,
                onChanged: (int value) {
                  onChanged(value);
                },
                activeColor: Colors.red,
                subtitle: Text(
                  quiz.questions[counter].option4,
                )),
            RaisedButton(
                child: Text('Press Me'),
                onPressed: () {
                  print('counter is: $counter \n_selected is: $_selected');
                  setState(() {
                    onChanged(null);
                    if (counter < 5) {
                      counter++;
                    } else {
                      counter = 0;
                    }
                  });
                })
          ],
        ),
      ),
    );
  } return Center(child: CircularProgressIndicator());}
}

如果我设置quiz = quiz1,则会得到所需的行为,但使用future会返回null,那么在构建窗口小部件之前如何从json端点填充测验?使用initState似乎没有什么不同。

1 个答案:

答案 0 :(得分:2)

将作业包装到quiz中的setState

assignQuiz() async {
  Quiz newQuiz = Quiz(await fetchQuestion(http.Client()));
  setState(() {
    quiz = newQuiz;
  });
}