Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- dependencies:
- flutter:
- sdk: flutter
- http: ^0.13.6
- provider: ^6.1.1
- file api_service.dart
- import 'package:http/http.dart' as http;
- import 'dart:convert';
- class ApiService {
- Future<List<dataCrypto>> bacaApi() async {
- final response = await http.get(Uri.parse('https://api.coinlore.net/api/tickers/'));
- if(response.statusCode == 200){
- final List<dynamic> dataList = json.decode(response.body)['data'];
- List<dataCrypto> cryptoList = dataList.map((data) => dataCrypto.fromJson(data)).toList();
- return cryptoList;
- }else{
- throw Exception('Gagal baca data');
- }
- }
- }
- class dataCrypto {
- final String id;
- final String symbol;
- final String name;
- dataCrypto({
- required this.id,
- required this.symbol,
- required this.name,
- });
- factory dataCrypto.fromJson(Map<String, dynamic> json){
- return dataCrypto(
- id: json['id'],
- symbol: json['symbol'],
- name: json['name'],
- );
- }
- }
- file provider_crypto.dart
- import 'package:flutter/material.dart';
- import 'api_service.dart';
- class ProviderCrypto extends ChangeNotifier {
- final ApiService apiService = ApiService();
- List<dataCrypto> cryptoList = [];
- Future<void> ambilApi() async {
- try {
- cryptoList = await apiService.bacaApi();
- notifyListeners();
- } catch (e) {
- print('Error: $e');
- }
- }
- }
- file main.dart
- import 'package:flutter/material.dart';
- import 'package:provider/provider.dart';
- import 'provider_crypto.dart';
- void main() {
- runApp(
- ChangeNotifierProvider(
- create: (context) => ProviderCrypto(),
- child: MyApp(),
- ),
- );
- }
- class MyApp extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- home: MyHomePage(),
- );
- }
- }
- class MyHomePage extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- final cryptoProvider = Provider.of<ProviderCrypto>(context);
- return Scaffold(
- appBar: AppBar(
- title: Text('Crypto List'),
- ),
- body: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- SizedBox(height: 10),
- ElevatedButton(
- onPressed: () {
- cryptoProvider.ambilApi();
- },
- child: Text('Ambil Data'),
- ),
- SizedBox(height: 20),
- Expanded(
- child: ListView.builder(
- itemCount: cryptoProvider.cryptoList.length,
- itemBuilder: (context, index) {
- final crypto = cryptoProvider.cryptoList[index];
- return Card(
- child: ListTile(
- leading: Text(
- crypto.symbol,
- style: TextStyle(
- color: Colors.blue,
- fontSize: 15,
- ),
- ),
- title: Text(crypto.name+' ('+crypto.id+')'),
- ),
- );
- },
- ),
- ),
- ],
- ),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement