誰能告訴我如何在flutter中決議這個JSON。我被困住了我成功地創建了類,但是從決議方法中得到錯誤這是JSON
{
"btcinr": {
"base_unit": "btc",
"quote_unit": "inr",
"low": "3001337.0",
"high": "3145000.0",
"last": "3107312.0",
"type": "SPOT",
"open": "3085453",
"volume": "243.1121",
"sell": "3114335.0",
"buy": "3106628.0",
"at": 1646663606,
"name": "BTC/INR"
}
}
我陷入困境并出現錯誤的方法是
Future<List<Map<String, dynamic>>> fetchData() async {
final response =
await http.get(Uri.parse("https://api.wazirx.com/api/v2/tickers"));
if (response.statusCode == 200) {
final responseJson = json.decode(response.body);
} else {
throw Exception('Unexpected Error Occured!');
}
}
此方法不完整,任何幫助將不勝感激謝謝!
uj5u.com熱心網友回復:
老實說,這是一個有點籠統的問題。但我會盡力回答我的理解。如果要創建json決議機制。您可以使用
示例代碼
// To parse this JSON data, do
//
// final bricklink = bricklinkFromJson(jsonString);
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(title: 'Scanner'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
int myvalue = 0;
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
@override
void initState() {}
Future<int> functions() async {
// do something here
return Future.value();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Scanner"),
backgroundColor: Colors.green,
),
body: FutureBuilder(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
List<Map<String, dynamic>> data =
snapshot.data as List<Map<String, dynamic>>;
return Container(
color: Colors.white,
child: ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text((data[index] as Map<String, dynamic>)
.keys
.single
.toString()),
subtitle: Text((data[index] as Map<String, dynamic>)
.values
.single
.toString()),
leading: CircleAvatar(
child: Text((data[index] as Map<String, dynamic>)
.keys
.single[0]
.toString())),
);
},
),
);
} else {
return Center(
child: Container(
height: 50,
width: 50,
child: CircularProgressIndicator(),
),
);
}
}),
);
}
}
class Page1 extends StatelessWidget {
var _controller = TextEditingController();
Page1({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: Container(
height: 55,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green)),
onPressed: () {},
child: Text(
"Choose the Date",
style: TextStyle(fontSize: 25),
)),
),
),
Center(
child: Text(
"No date Choosen",
style: TextStyle(fontSize: 16),
),
),
Center(
child: Wrap(
// direction: Axis.vertical,
children: [
RadioListTile(
title: Text("home"),
value: "Home",
groupValue: "Home",
onChanged: (v) {}),
RadioListTile(
title: Text("Company"),
value: "Company",
groupValue: "Home",
onChanged: (v) {}),
RadioListTile(
title: Text("Other"),
value: "Other",
groupValue: "Home",
onChanged: (v) {}),
],
),
),
Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _controller,
decoration: InputDecoration(
hintText: "Enter the number of bottels",
border: OutlineInputBorder(),
),
),
),
),
Container(
// height: 75,
padding: EdgeInsets.symmetric(horizontal: 50),
child: Row(
children: [
Expanded(
child: Container(
height: 55,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.green)),
onPressed: () {},
child: Text(
"Start",
style: TextStyle(fontSize: 25),
)),
),
),
],
),
)
],
);
}
}
Future<List<Map<String, dynamic>>> fetchData() async {
final response =
await get(Uri.parse("https://api.wazirx.com/api/v2/tickers"));
if (response.statusCode == 200) {
Map<String, dynamic> responseJson = json.decode(response.body);
// print(responseJson.runtimeType);
List<Map<String, dynamic>> list = [];
var cd = responseJson.forEach((key, value) {
Map<String, dynamic> value2 = Map.of({key: value});
list.add(value2);
});
return list;
} else {
throw Exception('Unexpected Error Occured!');
}
}
uj5u.com熱心網友回復:
按照您的 json 物件結構,您的fetchData方法應該具有回傳型別,Map<String, Map<String, dynamic>>因為它是 Map 的 Map。
更新回傳型別后,您的代碼中缺少的部分是將解碼的轉換response.body為Map<String, Map<String, dynamic>>.
請參閱下面的解決方案。
解決方案:
Future<Map<String, Map<String, dynamic>>> fetchData() async {
final response =
await http.get(Uri.parse("https://api.wazirx.com/api/v2/tickers"));
if (response.statusCode == 200) {
final responseJson = (json.decode(response.body) as Map).map(
(key, value) => MapEntry(key as String, value as Map<String, dynamic>));
return responseJson;
} else {
throw Exception('Unexpected Error Occured!');
}
}
在 ListView 生成器中
您可以使用上面的方法在 ListView 構建器中顯示資料,FutureBuilder如下所示:
FutureBuilder<Map<String, Map<String, dynamic>>>(
future: fetchData(),
builder: (BuildContext context,
AsyncSnapshot<Map<String, Map<String, dynamic>>> snapshot) {
if (snapshot.data == null) {
return const Center(child: CircularProgressIndicator());
}
final data = snapshot.data;
return ListView.builder(
itemBuilder: ((context, index) {
final item = data!.entries.elementAt(index);
final map = item.value;
final String baseUnit = map['base_unit'];
final String quoteUnit = map['quote_unit'];
final String high = map['high'];
final String low = map['low'];
return ListTile(
title: Text(baseUnit),
subtitle: Text('High-$high$quoteUnit Low - $low$quoteUnit'),
);
}),
itemCount: data!.entries.length,
);
},
),
下面是上面代碼生成的 UI 截圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/439303.html
上一篇:錯誤:沒有找到類org.json.JSONObject的序列化程式,也沒有找到創建BeanSerializer的屬性
