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

10,357

Solution 1

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 2

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

Future<List<Question>> newQuestions = getData();
Share:
10,357

Related videos on Youtube

DittoGod
Author by

DittoGod

Updated on June 04, 2022

Comments

  • DittoGod
    DittoGod almost 2 years
    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?

    • Saed Nabil
      Saed Nabil about 4 years
      List<Question> newQuestions = await getData(); you probably missed 'await' keyword