Maps in Flutter are used to store data as Key-Value pairs. So that the data can be access from the map using the specific key. Let’s see how to create a Map in Flutter – it will be a collection of key-value pairs. Also, we will be seeing how to push/add an item to Map.
Sample Map data:
Map<String, int> = {'BTC': 5, 'ETH': 1, 'LTC': 2};
Creating a new Map in Flutter – Dart Code
Here is the code in flutter – creating an empty map named coinPrice
Map<String, String> coinPrice = {};
Add a new item Map in Flutter – Dart Code
coinPrice['BTC'] = "345345";
Full Code:
const List<String> cryptoList = [ 'BTC', 'ETH', 'LTC', ]; const coinAPIURL = 'https://rest.coinapi.io/v1/exchangerate'; const apiKey = '5CACF267-0607-425B-B875-FBA947VCB321'; class CoinData { Future getCoinData(String selectedCurrency) async { Map<String, String> coinPrice ={}; //creating empty map for (String coin in cryptoList) { String requestURL = '$coinAPIURL/$coin/$selectedCurrency?apikey=$apiKey'; http.Response response = await http.get(requestURL); if (response.statusCode == 200) { var decodedData = jsonDecode(response.body); var lastPrice = decodedData['rate']; coinPrice['$coin'] = lastPrice.toStringAsFixed(0); //adding new item to map print(coinPrice); } else { print(response.statusCode); throw 'Problem with the get request'; } } return coinPrice; //returning map data } }