如何在Flutter中创建该自定义流程图?
Flutter 自定义流程图实现方案
方案一:使用flutter_flow_chart包(高灵活性)
这个包支持自定义节点样式、连线样式,适配复杂流程图需求,比你试过的工具更灵活。
- 安装依赖
在pubspec.yaml中添加:
dependencies: flutter_flow_chart: ^0.3.0
- 基础实现示例
import 'package:flutter/material.dart'; import 'package:flutter_flow_chart/flutter_flow_chart.dart'; class CustomFlowChart extends StatefulWidget { @override _CustomFlowChartState createState() => _CustomFlowChartState(); } class _CustomFlowChartState extends State<CustomFlowChart> { late FlowChartController controller; @override void initState() { super.initState(); controller = FlowChartController(); // 添加节点 final node1 = Node( position: const Offset(100, 100), size: const Size(150, 60), label: const Text('起始节点'), color: Colors.blue.shade100, ); final node2 = Node( position: const Offset(100, 220), size: const Size(150, 60), label: const Text('分支节点'), color: Colors.green.shade100, ); controller.addNode(node1); controller.addNode(node2); // 添加连线 controller.addConnection( Connection( fromNode: node1, fromPort: PortPosition.bottom, toNode: node2, toPort: PortPosition.top, color: Colors.black, ), ); } @override Widget build(BuildContext context) { return Scaffold( body: FlowChart( controller: controller, onNodePositionChanged: (node, position) => setState(() {}), ), ); } }
方案二:自定义CustomPainter(完全定制)
如果现有包都满足不了需求,直接用CustomPainter手绘是最灵活的方式,能实现任何你想要的流程图样式。
- 自定义绘制类
class FlowChartPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { final paint = Paint()..color = Colors.black; final textPainter = TextPainter( textDirection: TextDirection.ltr, ); // 绘制节点1 canvas.drawRect( const Rect.fromLTWH(100, 100, 150, 60), paint..color = Colors.blue.shade100, ); textPainter.text = const TextSpan( text: '起始节点', style: TextStyle(color: Colors.black, fontSize: 16), ); textPainter.layout(); textPainter.paint(canvas, const Offset(140, 115)); // 绘制节点2 canvas.drawRect( const Rect.fromLTWH(100, 220, 150, 60), paint..color = Colors.green.shade100, ); textPainter.text = const TextSpan( text: '分支节点', style: TextStyle(color: Colors.black, fontSize: 16), ); textPainter.layout(); textPainter.paint(canvas, const Offset(140, 235)); // 绘制带箭头的连线 paint.color = Colors.black; canvas.drawLine( const Offset(175, 160), const Offset(175, 220), paint, ); // 绘制箭头 final path = Path(); path.moveTo(175, 220); path.lineTo(170, 210); path.lineTo(180, 210); path.close(); canvas.drawPath(path, paint); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) => false; }
- 使用自定义绘制
class CustomFlowChart extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: CustomPaint( painter: FlowChartPainter(), size: const Size(double.infinity, double.infinity), ), ); } }
如果你的流程图有复杂分支、条件判断或交互需求,可以基于上述示例扩展:比如给节点添加点击事件、动态调整布局、支持节点拖拽等。
内容的提问来源于stack exchange,提问作者Moses
相关产品推荐
相关产品推荐

