根据api响应创建一个饼图



我想使用API响应创建一个饼图,但它不起作用以下是我获取数据的方法:

Future getPie() async{
final response = await http.get(Uri.parse("url"));
final js = jsonDecode(response.body);
return js;
}

然后我在未来的建设者中创建馅饼

FutureBuilder(
future: getPie(),
builder: (ctx,AsyncSnapshot ss){
if(ss.hasData){
return SingleChildScrollView(
child: Container(
child: Center(
child: PieChart(
dataMap: ss.data,
chartRadius: MediaQuery.of(context).size.width / 1.7,
legendOptions: LegendOptions(
legendPosition: LegendPosition.bottom
),

)
),
)
);
}else{
return Center(child: CircularProgressIndicator());
}
}
),

这是API响应

{ 
'a' : 2
'b' : 5
}

但是我得到一个错误:

type'_InternalLinkedHashMap<字符串,动态>'不是类型"Map<字符串,双>'

我也尝试过使用地图,但手动工作,从API没有:

Future getPie() async{

final response = await http.get(Uri.parse("url"));
final js = jsonDecode(response.body);
final  a= js['a'];
final  b= js['b'];
//this work
final Map<String, double> data = {};
data['a'] = 4;
data['b'] = 5;
//this doesn't
final Map<String, double> data = {};
data['a'] = a;
data['b'] = b;
print(data);
return data;
}

改为执行以下操作:

Future getPie() async {
final response = await http.get(Uri.parse("url"));
final js = jsonDecode(response.body);
var res = Map.fromEntries(js.entries.map((e) => MapEntry<String, double>(e.key, e.value.toDouble())));
return res;
}

最新更新