移动方块

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  int _page = 0;
  @override
  Widget build(BuildContext context) {
    const bgColor = [Colors.red,Colors.green,Colors.yellow];
    bool isCheck = true;
    return MaterialApp(
        home: HomePage()
    );
  }

}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int num = 1;
  double _left = 0;
  double _top = 0;
  double _maxWidth = 0;
  double _maxHeight = 0;
  double _width = 300;
  double _height = 200;
  TextEditingController _controll=TextEditingController();
  GlobalKey _gKey = GlobalKey();
  @override
  void initState() {
    super.initState();
    
    WidgetsBinding.instance.addPostFrameCallback((_){
      print("addPostFrameCallback");
      //初始获取手机屏幕宽高
      _maxWidth = _gKey.currentContext.size.width;
      _maxHeight = _gKey.currentContext.size.height;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('LOL',style: TextStyle(color: Colors.yellow),),
      ),
      body: GestureDetector(
        onPanUpdate: (DragUpdateDetails details){
          setState(() {
            _left += details.delta.dx;
            _top += details.delta.dy;

            //设定移动范围
            if(_left > _maxWidth - 200)
              _left = _maxWidth - 200;
            if(_top > _maxHeight - 200)
              _top = _maxHeight - 200;
            if(_left < 0)
              _left = 0;
            if(_top < 0)
              _top = 0;
          });
        },
        child: Stack(
          key: _gKey,
          children: <Widget>[
            Positioned(
              left: _left,
              top: _top,
              width: 200,
              height: 200,
              child: Container(
                color: Colors.yellow,
              ),
            )
          ],
        ),
      ),
    );
  }

}

 

posted @ 2020-08-16 16:24  蜗牛的礼物  阅读(102)  评论(0编辑  收藏  举报