Skip to content

Instantly share code, notes, and snippets.

@rodolfofranco
Created May 24, 2020 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodolfofranco/8efd36ed5ed5c5f1971e614a41b40ed8 to your computer and use it in GitHub Desktop.
Save rodolfofranco/8efd36ed5ed5c5f1971e614a41b40ed8 to your computer and use it in GitHub Desktop.
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'models/country.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
//We create our list of Country.
List<Country> countries = List();
//We create a boolean variable to check when data is loading.
bool loading = false;
getCountries() async {
try {
final response = await Dio().get('https://restcountries.eu/rest/v2/all');
//We use json.decode function in order to transform our response into a dynamic object.
final data = response.data;
//We iterate our array response and we add each object to our Country list.
data.forEach((o) => {countries.add(Country.fromMap(o))});
//We change our loading state to false to indicate that the data has been fetched.
setState(() {
loading = false;
});
} catch (err) {
setState(() {
loading = false;
});
//We handle our exception if something happens
}
}
@override
void initState() {
// TODO: implement initState
super.initState();
loading = true;
getCountries();
}
@override
Widget build(BuildContext context) {
return Scaffold(
//We check if the data is loading. If it's loading we return a circular progress indicator, if not we return our list of countries.
body: loading
? Center(child: CircularProgressIndicator())
: ListView(
children: countries.map((country) {
return ListTile(
title: Text(country.name), subtitle: Text(country.capital));
}).toList()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment