如何将多个json对象添加/映射到dart对象
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get('https://cloud.iexapis.com/stable/stock/market/batch?symbols=SLVO,MONY&types=stats&token=');
/*String response = '''
{"AAPL":
{"stats":{"week52change":0.232986,"week52high":255.93,"week52low":142,"marketcap":1136677331400,"employees":137000,"day200MovingAvg":199.29,"day50MovingAvg":225.28,"float":4436680630.59,"avg10Volume":26482506.4,"avg30Volume":26817874.5,"ttmEPS":11.9342,"ttmDividendRate":3,"companyName":"Apple, Inc."
}
},
"FB":
{"stats":{"week52change":0.1,"week52high":255.93,"week52low":142,"marketcap":1136677331400,"employees":137000,"day200MovingAvg":199.29,"day50MovingAvg":225.28,"float":4436680630.59,"avg10Volume":26482506.4,"avg30Volume":26817874.5,"ttmEPS":11.9342,"ttmDividendRate":3,"companyName":"Apple, Inc."
}
}
}
''';*/
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
//final parsed = json.decode(responseBody).cast<Map<String,dynamic>>();
//return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
dynamic Obj = json.decode(responseBody);
print(Obj.length);
List<Photo> photoList = [];
Obj.forEach((k, v,z) => photoList.add(Photo(k,v,z)));
return photoList;
}
class Photo {
String symbol;
String companyName;
dynamic stats;
//dynamic stats;
Photo(this.symbol ,this.stats,this.companyName);
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'Isolate Demo';
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? PhotosList(photos: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
class PhotosList extends StatelessWidget {
final List<Photo> photos;
PhotosList({Key key, this.photos}) : super(key: key);
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: photos.length,
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.album),
title: Column( children: [
Text(photos[index].symbol),
Text(photos[index].companyName),
],
),
subtitle: Column(
children: [
// Text( ' ${photos[index].stats["stats"]["dividendYield"]["companyName"]}'),
// Text( ' ${photos[index].data["quote"]["iexRealtimePrice"]}' ' ${photos[index].stats["stats"]["dividendYield"]["companyName"]}'),
// Text( ' ${photos[index].data["quote"]["iexRealtimePrice"]}'),
Text ( '${photos[index].stats["dividendYield"] ?? ""}'),
],
),
//title: Text(photos[index].symbol),
//subtitle: Text( ' ${photos[index].stats["stats"]["dividendYield"]["companyName"]}'),
//subtitle: Text( ' ${photos[index].data["quote"]["iexRealtimePrice"]}' ' ${photos[index].stats["stats"]["dividendYield"]["companyName"]}'),
// subtitle: Text( ' ${photos[index].data["quote"]["iexRealtimePrice"]}'),
// subtitle: Text ( ' ${photos[index].stats["stats"]["dividendYield"]}'),
);
},
);
}
}
Json
{“SLVO”:{“stats”:{“week52change”:0.047256,“week52high”:7.48,“week52low”:6.23,“marketcap”:null,“employees”:null,“day200MovingAvg”:6.88,“day50MovingAvg”:7.13,“float”:null,“avg10Volume”:7454.8,“avg30Volume”:7927.83,“ttmEPS”:null,“ttvidendrate”:null,“companyName”:“Credit Suisse MDIX-Links白银股票担保ETN”,“sharesOutstanding”:0,“maxChangePercent”:58.7391,“year5ChangePercent”:-0.4128,“year2ChangePercent”:-0.1369,“year1ChangePercent”:0.047256,“ytdChangePercent”:-0.005789,“month6ChangePercent”:0.074445,“month3ChangePercent”:-0.035112,“month1ChangePercent”:-0.025532”,“day30ChangePercent”:-0.035112,“day5ChangePercent”:-0.007225,“nextDividendDate”:null,“dividendYield”:null,“nextearningdate”:null,“exDividendDate”:null,“peRatio”:null,“beta”:-0.06347545711182472},“报价:{”symbol:“SLVO”,“companyName:“瑞士信贷X-Links白银股票涵盖看涨ETN”,“primaryExchange:“NASDAQ”,“calculationPrice:“close”,“open”:6.89,“openTime”:1574346600589,“close”:6.88,“closeTime”:157437000242,“high”:6.9,“low”:6.87,“latestPrice”:6.88,“latestSource:“close”,“latestTime”:“11月21日,
添加:
错误
I/颤振(28411):异常:类型(动态、动态、动态)=
我已经修改了url来包含统计数据和引用
你不能使用两个动态,它的地图
,你仍然需要动态字段名
你可以添加令牌并用完整的代码运行,演示图片如下
代码片段
Text ( '${photos[index].data["stats"]["dividendYield"] ?? ""}'),
Text ( '${photos[index].data["stats"]["week52change"] ?? ""}'),
Text ( '${photos[index].data["quote"]["companyName"] ?? ""}'),
演示
完整代码
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get('https://cloud.iexapis.com/stable/stock/market/batch?symbols=SLVO,MONY&types=stats,quote&token=');
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
//final parsed = json.decode(responseBody).cast<Map<String,dynamic>>();
//return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
dynamic Obj = json.decode(responseBody);
print(responseBody);
print(Obj.length);
List<Photo> photoList = [];
Obj.forEach((k, v) => photoList.add(Photo(k,v)));
return photoList;
}
class Photo {
String symbol;
//String companyName;
dynamic data;
//dynamic quote;
Photo(this.symbol ,this.data);
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'Isolate Demo';
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? PhotosList(photos: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
class PhotosList extends StatelessWidget {
final List<Photo> photos;
PhotosList({Key key, this.photos}) : super(key: key);
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: photos.length,
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.album),
title: Column( children: [
Text(photos[index].symbol),
//Text(photos[index].companyName),
],
),
subtitle: Column(
children: [
// Text( ' ${photos[index].stats["stats"]["dividendYield"]["companyName"]}'),
// Text( ' ${photos[index].data["quote"]["iexRealtimePrice"]}' ' ${photos[index].stats["stats"]["dividendYield"]["companyName"]}'),
// Text( ' ${photos[index].data["quote"]["iexRealtimePrice"]}'),
Text ( '${photos[index].data["stats"]["dividendYield"] ?? ""}'),
Text ( '${photos[index].data["stats"]["week52change"] ?? ""}'),
Text ( '${photos[index].data["quote"]["companyName"] ?? ""}'),
],
),
//title: Text(photos[index].symbol),
//subtitle: Text( ' ${photos[index].stats["stats"]["dividendYield"]["companyName"]}'),
//subtitle: Text( ' ${photos[index].data["quote"]["iexRealtimePrice"]}' ' ${photos[index].stats["stats"]["dividendYield"]["companyName"]}'),
// subtitle: Text( ' ${photos[index].data["quote"]["iexRealtimePrice"]}'),
// subtitle: Text ( ' ${photos[index].stats["stats"]["dividendYield"]}'),
);
},
);
}
}
我刚刚试着分析firebase实时数据库中的数据。但在转换到模型时出现问题,我正在尝试解析来自Flatter上firebase数据库的数据。但是一个错误说 我的完整测验:{-M5-R3BqTajbCFk5mQuQ:{硬币: 434, isSubmit: true,问题:[{答案: sddsd,名称:我们为什么使用它?,选项:[建立, adwada, adawda, sddsd],选择:},{答案:
WebAssembly enables load-time and run-time (dlopen) dynamic linking in the MVP by having multiple instantiated modules share functions, linear memories, tables and constants using module imports and e
在动态数组类型的情况下,数组的初始长度为零。 必须使用标准SetLength函数设置数组的实际长度,该函数将分配用于存储数组元素的必要内存。 声明动态数组 要声明动态数组,请不要提及数组范围。 例如 - type darray = array of integer; var a: darray; 在使用数组之前,必须使用setlength函数声明大小 - setlength(a,
动态模型定义具有dynamic segments的路由,Ember使用它来访问URL中的值。 动态段以:在route()方法中以:开头,后跟标识符。 必须使用模型中的id属性定义URL。 语法 (Syntax) Ember.Route.extend ({ model(params) { //code here } }); Router.map(function() {
动态SQL是iBATIS的一个非常强大的功能。 有时您必须根据参数对象的状态更改WHERE子句标准。 在这种情况下,iBATIS提供了一组动态SQL标记,可以在映射语句中使用,以增强SQL的可重用性和灵活性。 使用一些额外的标签将所有逻辑放入.XML文件中。 以下是SELECT语句以两种方式工作的示例 - 如果您传递了ID,那么它将返回与该ID相对应的所有记录。 否则,它将返回员工ID设置为NUL
Dynamic Normalizer 播放默认音量不同的乐曲或声音时,可自动调整音量等级美妙播放。 关 随原设音量播放 开 调整音量后播放