我有这个代码。我想要的是当我按下按钮时,map[food] 递增 1,这是饼图显示的 map ,我希望饼图使用新数据重新呈现。忽略切换,我现在不使用它。
这个饼图来自一个包,如果你想查看它,这是我添加到依赖项中的内容:pie_chart: ^0.8.0
和 this is it .
import 'package:flutter/material.dart';
import 'package:pie_chart/pie_chart.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool toggle = true;
Map<String, double> dataMap = new Map();
@override
void initState() {
super.initState();
dataMap.putIfAbsent("Food", () => 5);
dataMap.putIfAbsent("Gas", () => 3);
dataMap.putIfAbsent("Transportation", () => 2);
dataMap.putIfAbsent("Games", () => 2);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Pie Chart"),
),
body: Container(
child: Center(
child: toggle
? PieChart(
dataMap: dataMap,
legendFontColor: Colors.blueGrey[900],
legendFontSize: 14.0,
legendFontWeight: FontWeight.w500,
animationDuration: Duration(milliseconds: 800),
chartLegendSpacing: 32.0,
chartRadius: MediaQuery.of(context).size.width / 2.7,
showChartValuesInPercentage: true,
showChartValues: true,
chartValuesColor: Colors.blueGrey[900].withOpacity(0.9),
)
: Text("Press FAB to show chart"),
),
),
floatingActionButton: FloatingActionButton(
onPressed: add,
child: Icon(Icons.insert_chart),
),
);
}
void togglePieChart() {
setState(() {
toggle = !toggle;
});
}
void add(){
setState(() {
dataMap["Food"]++;
debugPrint(dataMap["Food"].toString());
});
}
}
最佳答案
问题出在包本身。它仅在 initState()
方法中进行百分比计算,该方法仅在创建 PieChart 实例时调用。
您可以自己编辑包代码,并在 _PieChartState
类的 build
方法中添加这两行:
initLegends();
initValues();
关于flutter - 为什么 setState 不使用差异输入重建小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55552749/