Kevin Yang
Kevin Yang

Reputation: 737

flutter) How do I create a widgets in a tabbed position of screen?

I am developing a whiteboard app.

I would like to create text box widgets at the potision I want as shown in the image below. May I know how to create a widget in the position(offset) where I've tapped?

enter image description here

Upvotes: 1

Views: 187

Answers (1)

Tuan
Tuan

Reputation: 2433

As i comment before. I have an idea: using GestureDetector to detect Tap action and postion of Tap, then using Stack and Positioned to create an Editor like this.

* localPosition and globalPosition is differences, carefull.

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  var editorEnable = false;
  var editorPosition = Offset.zero;

  void closeEditor() {
    print('editor closed');
    setState(() {
      editorEnable = false;
      editorPosition = Offset.zero;
    });
  }

  void newEditorAt(Offset position) {
    print('editor created at $position');
    setState(() {
      editorEnable = true;
      editorPosition = position;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: GestureDetector(
        onTapUp: (details) {
          if (editorEnable) {
            closeEditor();
          } else {
            newEditorAt(details.localPosition);
          }
        },
        child: Stack(
          fit: StackFit.expand,
          children: [
            Container(color: Colors.grey),
            if (editorEnable)
              Positioned(
                left: editorPosition.dx,
                top: editorPosition.dy,
                child: TextEditor(),
              ),
          ],
        ),
      ),
    );
  }
}

class TextEditor extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      width: 200,
      height: 50,
      child: TextField(
        autofocus: true,
      ),
    );
  }
}

And here is result

enter image description here

Upvotes: 3

Related Questions