Flutter
import 'package:country_house/pages/Country.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
class AllCountries extends StatefulWidget {
const AllCountries({Key? key}) : super(key: key);
@override
State<AllCountries> createState() => _AllCountriesState();
}
class _AllCountriesState extends State<AllCountries> {
Future<List> countries=[];
Future<List> getCountries() async {
var response = await Dio().get('https://restcountries.com/v3.1/all');
return response.data.length;
}
@override
void initState() {
countries = getCountries();
super.initState();
}
@override
Widget build(BuildContext context) {
getCountries();
return Scaffold(
appBar: AppBar(
title: Text('All Countries'),
centerTitle: true,
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: FutureBuilder<List>(
future: countries,
builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
if (snapshot.hasData) {
return Text('hello');
}
return null;
}),
),
),
);
}
}
I get the following error: A value of type 'List' can't be assigned to a variable of type 'Future<List>'.
- 'List' is from 'dart:core'.
- 'Future' is from 'dart:async'. Future countries=[];
How can I resolve this issue?
CodePudding user response:
You have to declare countries
in this form:
Future<List> countries = Future.value([]);
class _AllCountriesState extends State<AllCountries> {
Future<List> countries = Future.value([]);
Future<List> getCountries() async {
var response = await Dio().get('https://restcountries.com/v2/all');
return response.data;
}
@override
void initState() {
countries = getCountries();
super.initState();
}
CodePudding user response:
You have to declare countries
as a late Future:
late Future<List> countries;
then, the initState() will work. Note that you are requesting the length of the response and not the data. In order to populate the list you should also parse the jSon data. You can read an example of networking in flutter using Dio at the following link: Networking in Flutter using Dio