简体   繁体   中英

Flutter: how to create moveable widget

I have tried to create a moveable text widget.

When I press on widget and start moving finger around screen (still pressing on widget), then position of widget should be also moved.

I have tried to do this with GestureDetector and Transform widgets.

Here is code:

import 'package:flutter/material.dart';

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

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

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



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

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            MoveText(),
          ],
        ),
      ),
    );
  }
}

class MoveText extends StatefulWidget{
  
  @override
  _MoveTextState createState() => _MoveTextState();
}

class _MoveTextState extends State<MoveText> {
  Offset offset = Offset(0.0, 0.0);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onLongPressMoveUpdate: (LongPressMoveUpdateDetails details) {
        print('${details.localPosition}');
      },
      onPanStart: (details){
      },
      onPanUpdate: (details){
        print('Pan update ${details.localPosition}');
        setState((){
          offset = details.localPosition;
        });
      },
      onPanCancel: (){
        print('Pan cancel');
      },
      child: Transform(
        transform: Matrix4.translationValues(offset.dx, offset.dy, 0.0),
        child: Container(
          height: 50,
          width: 200,
          color: Colors.yellow,
          child: Text('Some text for test'),
        ),
      ),
    );
  }
}

When I first tap on widget and start moving everything works great, but when I stop and want again to start moving, then onPanUpdate isn't called.

Does anyone have some solution for this problem?

What you need is a Draggable widget.

Visit for more info: https://api.flutter.dev/flutter/widgets/Draggable-class.html

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM