flutter 如何在窗口调整时更新OverlayEntry尺寸

5vf7fwbs  于 2023-05-29  发布在  Flutter
关注(0)|答案(2)|浏览(222)

bounty还有3天到期。此问题的答案有资格获得+50声望奖励。Mahesh Jamdade希望引起更多关注这个问题。

我试图显示一个覆盖的宽度相同的文本字段。下面的代码示例工作正常,但当我在浏览器中运行它并调整窗口大小时,文本字段会调整大小,但覆盖层仍保留旧的尺寸。
如何在调整窗口大小时更新(而不是重新渲染)覆盖的尺寸?
下面是我尝试过的示例代码

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final ScrollController _scrollController = ScrollController();

  Widget _list() {
    return Container(
      height: 5 * 40,
      child: Scrollbar(
          controller: _scrollController,
          thumbVisibility: true,
          child: ListView.builder(
              controller: _scrollController,
              padding: EdgeInsets.zero,
              itemCount: 20,
              itemBuilder: (context, index) => ListTile(
                    title: Text('item $index'),
                    onTap: () {
                      _overlayEntry.remove();
                    },
                  ))),
    );
  }

  final LayerLink _layerLink = LayerLink();

  OverlayEntry _createOverlay() {
    final renderBox = context.findRenderObject() as RenderBox;
    final size = renderBox.size;
    final offset = renderBox.localToGlobal(Offset.zero);
    return OverlayEntry(
        builder: (context) => Positioned(
              left: offset.dx,
              width: size.width,
              child: CompositedTransformFollower(
                  offset: Offset(0, 50),
                  link: _layerLink,
                  child: Material(color: Colors.red, child: _list())),
            ));
  }

  late OverlayEntry _overlayEntry;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _overlayEntry = _createOverlay();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CompositedTransformTarget(
              link: _layerLink,
              child: TextFormField(
                decoration: InputDecoration(
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.black.withOpacity(0.8),
                    ),
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.red),
                  ),
                ),
                onTap: () {
                   if (_overlayEntry.mounted) {
                        _overlayEntry.remove();
                   }
                   Overlay.of(context).insert(_overlayEntry);
                },
                onChanged: (query) {},
              ),
            ),
          ],
        ),
      ),
    );
  }
}

下面是上述代码的输出

  • 请注意,覆盖尺寸与窗口大小不匹配(调整窗口大小时)*

我们可以通过调整Positioned.right参数来强制叠加尺寸

OverlayEntry(
        builder: (context) => Positioned(
              left: 0,
              right: 0, // custom offset from right
              // width: textFieldSize.width,
              child: CompositedTransformFollower(
                  offset: Offset(0, 50),
                  link: _layerLink,
                  child: Material(color: Colors.red, child: _list())),
            ));

但是如果我们在Textfield周围给予填充,例如,如果我设置Positioned.right:0并在Textfield周围提供填充,则覆盖层将始终占据整个宽度,这将失败。

我尝试的最后一个解决方案是将文本字段的宽度设置为覆盖宽度,但我不确定如何更新文本字段渲染框,以便覆盖占用预期的尺寸。

OverlayEntry _createOverlay() {
    /// textfield dimensions
    final textFieldRenderBox =
        textFieldKey.currentContext!.findRenderObject() as RenderBox;
    final textFieldOffset = textFieldRenderBox.localToGlobal(Offset.zero);
    final textFieldSize = textFieldRenderBox.size;
    print('$textFieldSize $textFieldOffset ');
    return OverlayEntry(
        builder: (context) => Positioned(
              left: 0,
              width: textFieldSize.width,
              child: CompositedTransformFollower(
                  offset: Offset(0, 50),
                  link: _layerLink,
                  child: Material(color: Colors.red, child: _list())),
            ));
  }

编辑:我尝试使用didChangeMetrics监听MediaQueyChanges并使用ValueListenableBuilder更新Overlay,但它的janky和更新延迟如下输出和代码

jhkqcmku

jhkqcmku1#

我认为你的用例可以通过使用自动完成小部件来解决,你试过了吗?

class Autocomplete<T extends Object> extends StatelessWidget {

will会给你看这样的东西
enter image description here

pgpifvop

pgpifvop2#

我们可以使用flutter3.10中引入的新小部件OverLayPortal来解决这个问题。
最初在此回答https://github.com/flutter/flutter/issues/78746#issuecomment-1564893844

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(
          title: "My Home Page",
        ));
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.only(left:24.0,right:12.0),
              child: CustomWidget(),
            ),
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class CustomWidget extends StatefulWidget {
  const CustomWidget({Key? key}) : super(key: key);
  @override
  State<CustomWidget> createState() => _CustomWidgetState();
}

class _CustomWidgetState extends State<CustomWidget> {
  final ScrollController _scrollController = ScrollController();

  Widget _list() {
    return Container(
      height: 5 * 40,
      child: Scrollbar(
          controller: _scrollController,
          thumbVisibility: true,
          child: ListView.builder(
              controller: _scrollController,
              padding: EdgeInsets.zero,
              itemCount: 20,
              itemBuilder: (context, index) => ListTile(
                    title: Text('item $index'),
                    onTap: () {
                      _portalController.hide();
                    },
                  ))),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  GlobalKey gkey = GlobalKey();
  final OverlayPortalController _portalController = OverlayPortalController();
  @override
  Widget build(BuildContext context) {
    Widget textfield() => TextFormField(
          key: gkey,
          decoration: InputDecoration(
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(
                color: Colors.black.withOpacity(0.8),
              ),
            ),
            border: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.red),
            ),
          ),
          onTap: () {
            if (!_portalController.isShowing) {
              _portalController.show();
            }
          },
          onChanged: (query) {},
        );
    
    return OverlayPortal(
      controller: _portalController,
      overlayChildBuilder: (BuildContext context) {
        final renderBox = gkey.currentContext!.findRenderObject() as RenderBox;
        final Size tSize = renderBox.size;
        final Offset offset = renderBox.localToGlobal(Offset.zero);
        return Positioned(
          left: offset.dx,
          top: offset.dy + tSize.height, // + textfield height
          child: Material(
            color: Colors.red,
            child: SizedBox(
              width: tSize.width,
              child: _list(),
            ),
          ),
        );
      },
      child: textfield(),
    );
  }
}

相关问题