颤动的可拖动小部件-始终在拖动时创建子级

时间:2020-01-09 13:02:04

标签: flutter draggable

我正在尝试在我的Flutter应用中实现可拖动的小部件。 ImageWidget是一个statefulWidget,我想将其放入可拖动对象中。我已经将相同的imageWidget对象设置为子元素和Draggable小部件的反馈。当我拖动可拖动的小部件时,将始终调用ImageWidget的build方法。我该如何预防?


void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Offset position = Offset(0, 0);
  Widget _image;

  @override
  void initState() {
    super.initState();
    _image = ImageWidget();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: new Scaffold(
        appBar: AppBar(
          title: Text("Drag Image"),
        ),
        body: Container(
            child: Stack(
          children: [
            Positioned(
              top: position.dy,
              left: position.dx,
              child: Draggable(
                maxSimultaneousDrags: 1,
                child: _image,
                feedback: _image,
                childWhenDragging: Container(),
                onDragStarted: () {},
                onDragEnd: (DraggableDetails details) {
                  setState(() {
                    position =
                        Offset(details.offset.dx, details.offset.dy);
                  });
                },
              ),
            )
          ],
        )),
      ),
    );
  }
}

class ImageWidget extends StatefulWidget {
  @override
  _ImageWidgetState createState() => _ImageWidgetState();
}

class _ImageWidgetState extends State<ImageWidget> {
  @override
  Widget build(BuildContext context) {
    print("Inside the build method of ImageWidget");
    return Image.network(
        "https://image.shutterstock.com/image-photo/beautiful-water-drop-on-dandelion-260nw-789676552.jpg",
        width: 200,
        height: 200,);
  }
}

0 个答案:

没有答案