What the API is? use it with Flutter
API Using in Flutter.
to understand what the API is I will tell you this example.
When you using travel apps to get a plane ticket you will notice all results in all apps the same! how !!
first of all, add this dependency to your pubsbec.yaml :
http: ^0.12.2
then create an account on :
to get your Api key
Now let’s use this api key in out code :
// ignore_for_file: file_names
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
class HomeScreen extends StatefulWidget {
const HomeScreen({Key key}) : super(key: key);
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
var price = 0.0;
var name = 'Coin Name';
var symbol = 'Symbol';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.amber,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Spacer(),
Text(
name,
style: const TextStyle(
fontSize: 33,
color: Colors.black54,
fontWeight: FontWeight.w700),
),
const SizedBox(
height: 20,
),
Text(
symbol,
style: const TextStyle(
fontSize: 22,
color: Colors.black54,
fontWeight: FontWeight.w700),
),
const SizedBox(
height: 20,
),
Text(
price.toString(),
style: const TextStyle(
fontSize: 22,
color: Colors.black54,
fontWeight: FontWeight.w700),
),
const Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
FloatingActionButton(
onPressed: () {
_getPricesFromAPI('BTC');
},
child: const Text('BTC'),
),
FloatingActionButton(
onPressed: () {
_getPricesFromAPI('XRP');
},
child: const Text('XRP'),
),
FloatingActionButton(
onPressed: () {
_getPricesFromAPI('DOGE');
},
child: const Text('DOGE'),
),
FloatingActionButton(
onPressed: () {
_getPricesFromAPI('ADA');
},
child: const Text('ADA'),
),
],
),
const Spacer(),
],
),
),
);
}
Future<dynamic> _getPricesFromAPI(coin) async {
const String apiKey = "1f67c62c-851d-4f68-8247-29f62afda190";
http.Response response = await http.get(
Uri.encodeFull(
"https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"),
headers: {"X-CMC_PRO_API_KEY": apiKey});
Map<String, dynamic> data = jsonDecode(response.body);
var coinFromJson = data['data'];
var res = coinFromJson.where((elem) =>
elem['symbol'].toString().toLowerCase().contains(coin.toLowerCase()));
List<dynamic> coinData = List<dynamic>.from(res);
print(coinData);
setState(() {
name = coinData[0]['name'];
symbol = coinData[0]['symbol'];
price = coinData[0]['quote']['USD']['price'];
});
}
}
Thank you so much and don’t forget to support me by clapping to the story and following me here
WebSite: https://codewithammar.com/ Medium: https://codewithammar.medium.com/ Twitter: https://twitter.com/codewithammar/ Facebook: https://m.facebook.com/codewithammar/ Instagram: https://instagram.com/codewithammar/ Telegram: https://t.me/codewithammar/ Mobile Apps development instructor : Ammar Awni