80 lines
1.9 KiB
Dart
80 lines
1.9 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter/material.dart';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
Future<Btcusdt> fetchBtcusdt() async {
|
|
final response =
|
|
await http.get(Uri.https('api.binance.com', 'api/v3/ticker/24hr'));
|
|
if (response.statusCode == 200) {
|
|
return Btcusdt.fromJson(jsonDecode(response.body));
|
|
} else {
|
|
throw Exception('Failed to load Btcusdt');
|
|
}
|
|
}
|
|
|
|
class Btcusdt {
|
|
final double? valuebtc;
|
|
Btcusdt({required this.valuebtc});
|
|
|
|
factory Btcusdt.fromJson(List<dynamic> json) {
|
|
return Btcusdt(
|
|
valuebtc: double.parse(json
|
|
.where((element) => element['symbol'].contains("BTCUSDT"))
|
|
.toList()
|
|
.first['lastPrice']));
|
|
}
|
|
}
|
|
|
|
void main() => runApp(MyApp());
|
|
|
|
class MyApp extends StatefulWidget {
|
|
MyApp({Key? key}) : super(key: key);
|
|
|
|
@override
|
|
_MyAppState createState() => _MyAppState();
|
|
}
|
|
|
|
class _MyAppState extends State<MyApp> {
|
|
late Future<Btcusdt> futureBtcusdt;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
futureBtcusdt = fetchBtcusdt();
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return MaterialApp(
|
|
title: 'Fetch Data Example',
|
|
theme: ThemeData(
|
|
primarySwatch: Colors.blue,
|
|
),
|
|
home: Scaffold(
|
|
appBar: AppBar(
|
|
title: Text('Fetch Data Example'),
|
|
),
|
|
body: Center(
|
|
child: FutureBuilder<Btcusdt>(
|
|
future: futureBtcusdt,
|
|
builder: (context, snapshot) {
|
|
if (snapshot.hasData) {
|
|
return Text(snapshot.data!.valuebtc.toString(),
|
|
style: TextStyle(fontSize: 15));
|
|
} else if (snapshot.hasError) {
|
|
return Text(
|
|
"${snapshot.error}",
|
|
style: TextStyle(fontSize: 15),
|
|
);
|
|
}
|
|
return CircularProgressIndicator();
|
|
},
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|