简体   繁体   中英

How to drag positioned widget inside a stack widget in flutter

I'm creating an application in which the user can drag his text over an image and can generate that image. I can drag text widget over an image, but the problem is that the text goes out of the screen if we drag it to the end in any direction(top, left, bottom, right). And I want that if the text is larger and the user drags it to the right, it will arrange it to the next line automatically.

This is the feature that I want. Please visit memegenerator ,

Code

import 'package:flutter/material.dart';

class DesignScreen extends StatefulWidget {
  final String formData;

  const DesignScreen({Key? key, required this.formData}) : super(key: key);

  @override
  State<DesignScreen> createState() => _DesignScreenState();
}

class _DesignScreenState extends State<DesignScreen> {
  Offset _offset = Offset.zero;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Design"),
      ),
      body: Column(
        children: [
          GestureDetector(
            child: Stack(
              children: [
                Image.asset(
                  "assets/images/oneIO.jpg",
                  width: double.infinity,
                ),
                Positioned(
                  top: _offset.dy,
                  left: _offset.dx,
                  child: FittedBox(
                    fit: BoxFit.contain,
                    child: Text(widget.formData),
                  ),
                ),
              ],
            ),
            onPanUpdate: (details) {
              setState(() {
                _offset = Offset(_offset.dx + details.delta.dx,
                    _offset.dy + details.delta.dy);
              });
            },
          )
        ],
      ),
    );
  }
}

They go out-of-screen because their top and left properties are either too small or too large. You can use clamp function to limit the offset to a range. For example:

  Positioned(
    top: _offset.dy.clamp(0, 200),
    left: _offset.dx.clamp(0, 200),
    child: ...
  )

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