Flutter仪表盘视图插件kdgaugeview的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter仪表盘视图插件kdgaugeview的使用

KdGaugeViewFlutter

KDGaugeView 是一个简单且可定制的仪表控件,灵感来源于 KdGaugeView,适用于Android。该库完全由Dart编写。

版本和许可证

  • pub package: pub package
  • License: License

Motivation

在Flutter应用中需要一个干净的仪表盘视图。

Getting Started

Installing

要在项目中使用kdgaugeview,首先需要将其添加到项目的pubspec.yaml文件中:

dependencies:  
  kdgaugeview: ^1.0.4

然后执行flutter pub get以安装依赖项。

Usage

导入库

在需要使用仪表盘视图的Dart文件中导入库:

import 'package:kdgaugeview/kdgaugeview.dart';

创建仪表盘组件

以下是一个简单的示例,展示了如何创建一个带有动画效果的仪表盘,并设置其最小值、最大值和初始速度:

GlobalKey<KdGaugeViewState> key = GlobalKey<KdGaugeViewState>();

KdGaugeView(
    key: key,
    minSpeed: 0,
    maxSpeed: 180,
    speed: 70,
    animate: true,
)

更新仪表盘的速度

可以通过调用updateSpeed方法来更新仪表盘的速度:

key.currentState.updateSpeed(120, animate: true, duration: Duration(milliseconds: 400));

Customization

可以根据需求自定义仪表盘的外观,以下是可配置的属性:

Property Type Description
speed double 初始速度
speedTextStyle TextStyle 速度文本样式

Screenshots

demo.jpg demo.gif

Author

  • Saurabh K Sharma - GIT

欢迎提出建议和改进意见。

Contributing

贡献步骤如下:

  1. Fork项目 (https://github.com/sorbh/kdgaugeViewflutter/fork)
  2. 创建特性分支 (git checkout -b feature/fooBar)
  3. 提交更改 (git commit -am 'Add some fooBar')
  4. 推送到分支 (git push origin feature/fooBar)
  5. 创建新的Pull Request

示例代码

下面是一个完整的示例代码,演示了如何在一个Flutter应用中使用kdgaugeview插件:

import 'package:flutter/material.dart';
import 'package:kdgaugeview/kdgaugeview.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'KdGaugeView Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title}) : super(key: key);

  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final speedNotifier = ValueNotifier<double>(10);
  final key = GlobalKey<KdGaugeViewState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title!),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              width: 400,
              height: 400,
              padding: EdgeInsets.all(10),
              child: ValueListenableBuilder<double>(
                  valueListenable: speedNotifier,
                  builder: (context, value, child) {
                    print(value);
                    return KdGaugeView(
                      key: key,
                      minSpeed: 0,
                      maxSpeed: 100,
                      speed: value,
                      animate: false,
                      alertSpeedArray: [40, 80, 90],
                      alertColorArray: [Colors.orange, Colors.indigo, Colors.red],
                      duration: Duration(seconds: 6),
                    );
                  }),
            ),
            ValueListenableBuilder<double>(
              valueListenable: speedNotifier,
              builder: (context, value, child) => Slider(
                onChanged: (value) {
                  key.currentState!.updateSpeed(value);
                  speedNotifier.value = value;
                },
                max: 200,
                min: 10,
                value: value,
              ),
            )
          ],
        ),
      ),
    );
  }
}

这段代码展示了一个包含滑块的页面,用户可以通过滑动滑块来动态更新仪表盘的速度。


更多关于Flutter仪表盘视图插件kdgaugeview的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter仪表盘视图插件kdgaugeview的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用kdgaugeview插件来创建仪表盘视图的示例代码。请注意,kdgaugeview可能不是一个真实存在的Flutter插件名称,因为我没有找到一个确切匹配的插件。然而,我将基于一个假想的仪表盘插件接口来展示如何使用它。如果你使用的是另一个具体的仪表盘插件,请参考该插件的官方文档进行适当调整。

首先,确保你已经在pubspec.yaml文件中添加了仪表盘插件的依赖项(这里以kdgaugeview作为示例名称,但你需要替换为实际插件的名称):

dependencies:
  flutter:
    sdk: flutter
  kdgaugeview: ^x.y.z  # 替换为实际插件的版本号

然后,运行flutter pub get来安装依赖项。

接下来,在你的Flutter应用中,你可以按照以下方式使用仪表盘插件:

import 'package:flutter/material.dart';
import 'package:kdgaugeview/kdgaugeview.dart'; // 导入仪表盘插件

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Gauge Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: GaugeScreen(),
    );
  }
}

class GaugeScreen extends StatefulWidget {
  @override
  _GaugeScreenState createState() => _GaugeScreenState();
}

class _GaugeScreenState extends State<GaugeScreen> {
  double _value = 50.0; // 仪表盘当前值

  void _updateValue(double newValue) {
    setState(() {
      _value = newValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Gauge Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SizedBox(
              height: 300,
              child: KDGaugeView(
                value: _value, // 设置仪表盘当前值
                maxValue: 100, // 设置仪表盘最大值
                needleColor: Colors.blue, // 设置指针颜色
                backgroundColor: Colors.grey[200], // 设置背景颜色
                circleColor: Colors.grey[300], // 设置外圈颜色
                textStyle: TextStyle(fontSize: 24, color: Colors.black), // 设置文本样式
              ),
            ),
            SizedBox(height: 20),
            Slider(
              value: _value.toDouble(),
              min: 0,
              max: 100,
              onChanged: _updateValue, // 更新仪表盘值
            ),
          ],
        ),
      ),
    );
  }
}

// 假设的 KDGaugeView 组件(实际使用时,请参考插件提供的组件)
class KDGaugeView extends StatelessWidget {
  final double value;
  final double maxValue;
  final Color needleColor;
  final Color backgroundColor;
  final Color circleColor;
  final TextStyle textStyle;

  KDGaugeView({
    required this.value,
    required this.maxValue,
    this.needleColor = Colors.black,
    this.backgroundColor = Colors.white,
    this.circleColor = Colors.grey,
    this.textStyle = const TextStyle(),
  });

  @override
  Widget build(BuildContext context) {
    // 这里是一个简化的仪表盘视图实现,实际插件可能有更复杂的实现
    return CustomPaint(
      size: Size.square(300.0),
      painter: _GaugePainter(
        value: value,
        maxValue: maxValue,
        needleColor: needleColor,
        backgroundColor: backgroundColor,
        circleColor: circleColor,
        textStyle: textStyle,
      ),
    );
  }
}

class _GaugePainter extends CustomPainter {
  final double value;
  final double maxValue;
  final Color needleColor;
  final Color backgroundColor;
  final Color circleColor;
  final TextStyle textStyle;

  _GaugePainter({
    required this.value,
    required this.maxValue,
    this.needleColor = Colors.black,
    this.backgroundColor = Colors.white,
    this.circleColor = Colors.grey,
    this.textStyle = const TextStyle(),
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = backgroundColor
      ..style = PaintingStyle.fill;
    canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);

    final circlePaint = Paint()
      ..color = circleColor
      ..strokeWidth = 10.0
      ..style = PaintingStyle.stroke;
    final radius = size.shortestSide / 2 - 10;
    canvas.drawCircle(size.center(Offset.zero), radius, circlePaint);

    final needleAngle = (value / maxValue) * 2 * 3.141592653589793;
    final needleLength = radius - 20;
    final needleBase = size.center(Offset.zero) -
        Offset(needleLength * 0.5 * math.cos(needleAngle), needleLength * 0.5 * math.sin(needleAngle));
    final needleTip = size.center(Offset.zero) +
        Offset(needleLength * math.cos(needleAngle), needleLength * math.sin(needleAngle));

    final needlePaint = Paint()
      ..color = needleColor
      ..strokeWidth = 5.0
      ..cap = StrokeCap.round;
    canvas.drawLine(needleBase, needleTip, needlePaint);

    final textPainter = TextPainter(
      text: TextSpan(
        text: '${value.toInt()}',
        style: textStyle.copyWith(color: Colors.black),
      ),
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr,
    );
    textPainter.layout(minWidth: 0, maxWidth: size.width);
    final textOffset = size.center(Offset.zero) - Offset(textPainter.width / 2, textPainter.height / 2);
    textPainter.paint(canvas, textOffset);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return oldDelegate != this;
  }
}

请注意,上面的代码包含了一个简化的自定义仪表盘视图KDGaugeView的实现,这仅用于展示目的。在实际项目中,你应该使用插件提供的仪表盘组件,而不是自定义绘制。此外,由于kdgaugeview可能不是一个真实存在的插件,你需要查找并安装一个实际的Flutter仪表盘插件,并根据其文档进行使用。

希望这个示例对你有所帮助!如果你有一个具体的仪表盘插件名称,请提供,我可以给出更精确的示例代码。

回到顶部