Created
May 24, 2020 00:32
-
-
Save rodolfofranco/8efd36ed5ed5c5f1971e614a41b40ed8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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