I want to create a chart widget which has three required properties.
Min value
Max value
value
so I can create multiple chart widget's in a Listview like this:
class home extends StatefulWidget {
const home({Key? key}) : super(key: key);
@override
State<home> createState() => _homeState();
}
class _homeState extends State<home> {
@override
Widget build(BuildContext context) {
return Container(
child: ListView(children: [gaugeChart(0, 100, cpuUsage), gaugeChart(0, 100, memoryUsage)]),
);
}
}
Inside the gaugeChart widget is a customPainter widget which needs the min, max and value at the end. If the value changes inside the setState it should update the widgets. So here's my question: How can I pass down these values to the customPainter function.
gaugeChart widget:
class gaugeChart extends StatefulWidget {
@override
State<gaugeChart> createState() => _gaugeChartState();
}
class _gaugeChartState extends State<gaugeChart> {
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: gaugeChartPainter(),
);
}
}
class gaugeChartPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// Inside here I need the min, max and value
}
}
I would suggest using Provider state management library.
First you need to define the provider in your main.dart. For example, wrap your MaterialApp in a MultiProvider widget and then define the providers property:
ChangeNotifierProvider<MyClass?>(
create: (_) => MyClass(),
),
Create a model class and a getter for each of your properties (make sure your class implements ChangeNotifier):
class MyClass with ChangeNotifier { // property here }
Inside of your build method in your stateful widget, make the provider listen to the changes: myClass= Provider.of<MyClass?>(context);
You can then access any of the properties that you defined in MyClass above throughout the whole app, with just adding the line of code from step 2 above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.