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

String opentdb = 'https://opentdb.com/api.php?amount=15&type=boolean';

class QuestionServices {
  Future<List<Question>> getData() async {
    List<Question> questions;
    String link = opentdb;
    var res = await http
        .get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
    print(res.body);
    if (res.statusCode == 200) {
      var data = json.decode(res.body);
      var rest = data['results'] as List;
      print(rest);
      questions =
          rest.map<Question>((json) => Question.fromJson(json)).toList();
    }
    print("List Size: ${questions.length}");
    // _questions = questions;
    return questions;
  }

  List<Question> newQuestions = getData();
}
class Question {
  final String question;
  final bool answer;

  Question({this.question, this.answer});

  factory Question.fromJson(Map<String, dynamic> json) {
    return Question(
      question: json['question'] as String,
      answer: json['correct_answer'] as bool,
    );
  }
}

I am trying to create a list of questions from a JSON database but whenever I try to get the returned list I get the error:

"A value of type 'Future<List<Question>>' can't be assigned to a variable of type 'List<Question>'."

I am unsure why the List I'm returning is giving out that error. Is there maybe a different way to get a json to a list?


Solution 1: Peter Haddad

getData returns a Future, therefore you need to do the following:

Future<List<Question>> newQuestions = getData();


Solution 2: Viren V Varasadiya

List<Question> getData() async { // remove Future
List<Question> questions;
String link = opentdb;
...

//how to access now you will get instance of List<Question>

getData().then((List<Question> newQuestions){

})


Solution 3: BK kumaran

Future<List<Question>>Listfetchdata() async{
final responsein = await http.get('https://opentdb.com/api.php?amount=15&amp;type=boolean');
final getindata = json.decode(responsein.body);
final getindata1 = json.encode(getindata['results']);
return compute(listdata,getindata1);
}

List<Question> listdata(String creation){ final parsed = jsonDecode(creation).cast<Map<String,dynamic>>(); return parsed.map<Question>((json)=>Question.fromJson(json)).toList(); }

List listitem; var maketolistarry=['']; void lastgettingdata() async{ final king=await Listfetchdata(); listitem=king.map((e) => e.category).toList(); maketolistarry=listitem; }

by help of maketolistarry you will get a list