Flutter 悬浮窗 OverlayEntry

import 'package:flutter/material.dart';

///
///悬浮窗
///
class Floating extends StatefulWidget {
  const Floating({Key? key}) : super(key: key);

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

class _FloatingState extends State<Floating> {
  // 创建OverlayEntry
  OverlayEntry _OverlayEntry = OverlayEntry(builder: (ctx) {
    return Container(
      child: MaterialApp(
          home: Scaffold(
              body: Container(
        height: 50,
        child: Column(
          children: [
            Text('data'),
            Text('data'),
            Text('data'),
          ],
        ),
      ))),
    );
  });

  @override
  Widget build(BuildContext context) {
    ///
    OverlayState? overlayState = Overlay.of(context);
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('悬浮窗'),
        ),
        body: Container(
          child: Center(
            child: Column(
              children: [
                TextButton(
                  style: ButtonStyle(),
                  onPressed: () {
                    // 往 Overlay 中插入插入OverlayEntry
                    overlayState!.insert(_OverlayEntry);
                  },
                  child: Text('显示悬浮窗'),
                ),

                ///***************************
                TextButton(
                  style: ButtonStyle(),
                  onPressed: () {
                    // 移除
                    this._OverlayEntry.remove();
                  },
                  child: Text('关闭悬浮窗'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
THE END
喜欢就支持一下吧
点赞14 分享