如何在flutter中连接两个小部件

时间:2019-06-30 09:02:57

标签: flutter flutter-layout

我想画一条连接两个小部件的直线,它应该由用户连接。

我尝试了什么。

import 'package:flutter/material.dart';

class Homedemo extends StatefulWidget {
  @override
  _HomedemoState createState() => _HomedemoState();
}

class _HomedemoState extends State<Homedemo> {

  List<Offset> points = <Offset>[];

  @override
  Widget build(BuildContext context) {

    final Container sketchArea = Container(
      margin: EdgeInsets.all(1.0),
      alignment: Alignment.topLeft,
      color: Colors.blueGrey[50],
      child: CustomPaint(
        painter: Sketcher(points),
      ),
    );

    return Container(
      child: Stack(
        children: <Widget>[
          GestureDetector(
            onPanUpdate: (DragUpdateDetails details) {
              setState(() {
               RenderBox box = context.findRenderObject();
                Offset point = box.globalToLocal(details.globalPosition);
                points[points.length-1] = point;
                print(points);
              });
            },
            onPanStart: (DragStartDetails details){
              setState(() {
                print("start");
                print(points);
                RenderBox box = context.findRenderObject();Offset point = box.globalToLocal(details.globalPosition);
                point = point.translate(0.0, -(AppBar().preferredSize.height));
                points = List.from(points)..add(point);
              });
            },
            onPanEnd: (DragEndDetails details) {
              setState(() {
              //  points.clear();
              });
              },
            child: sketchArea,
          ),

          Positioned(
            top: 50.0,
            left: 50.0,
            child: new Container(
                height: 50.0,
                width: 50.0,
                color: Colors.amberAccent,
              ),
          ),
          Positioned(
            top: 250.0,
            left: 350.0,
            child: new Container(
                height: 50.0,
                width: 50.0,
                color: Colors.green,
              ),
          ),
        ],
      ),

    );
  }
}


class Sketcher extends CustomPainter {

  final List<Offset> points ;

  Sketcher(this.points);

  @override
  bool shouldRepaint(Sketcher oldDelegate) {
    return true;
  }

  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.black
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 10.0;

    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null && points[i + 1] != null) {
        canvas.drawLine(points[i], points[i+1], paint);

      }
    }
  }
}

我能够画一条直线,但是我不知道如何准确地开始和停止,所以我看起来好像两个小部件都已连接。

0 个答案:

没有答案