Flutter OverlayEntry 类表示在 Flutter 应用中的一个叠加层

14 min read

OverlayEntry 类表示在 Flutter 应用中的一个叠加层。叠加层是一种特殊的组件,它会覆盖在当前页面之上,通常用于在应用中显示浮动框、模态窗口等内容。

要在 Flutter 应用中使用叠加层,首先需要在应用的根布局中添加一个 Overlay 组件。然后,可以通过调用 Overlay.of(context).insert() 方法向叠加层中插入一个 OverlayEntry 对象,来显示叠加层内容。例如:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  OverlayEntry _overlayEntry;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Overlay Demo'),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            // Create an OverlayEntry for the Overlay.
            _overlayEntry = OverlayEntry(
              builder: (context) => Positioned(
                left: 10,
                top: 10,
                child: Text('This is an Overlay'),
              ),
            );

            // Insert the OverlayEntry into the Overlay.
            Overlay.of(context).insert(_overlayEntry);
          },
          child: Text('Show Overlay'),
        ),
      ),
    );
  }
}