繁体   English   中英

解决了! Flutter、ListView.builder 在定位小部件中无法完全呈现在屏幕上并且无法使用 Expanded 或 Flexible 时? 小部件

[英]Solved! Flutter, ListView.builder doesn't renders fully on screen when in Positioned widget and can't use Expanded or Flexible? widgets

需要让 ListView.builder 在 RichText 小部件内的文本的某些部分下构建 ListTiles

使用 Stack 小部件执行此操作,我通过查找其偏移位置来获取 RichText 中元素的位置,为此需要使用 Key,尽管 TextSpan 没有 Key 属性,因此我在 RichText 中使用 InkWell 小部件(我想我可以关闭与之相关的动画)。

它工作得非常好,ListTiles 相应地遵循 InkWell(需要添加几行代码以使其无缝)。

虽然仍然存在大问题,但无法让 ListView.builder 显示 Text 小部件之外的项目,无法将其包装在 Extended() 或 Flexible() 小部件中,出现错误,父小部件使用不当,我认为是因为我使用 Stack 小部件并且不知道还能做什么。 请让我知道是否有人可以解决这个问题。

页面上有按钮,因此可以添加或删除文本,以查看其实际效果。 我在 ListTile 锚元素之前和之后添加了 Text 以便更好地查看它,因为它仅显示在 Text 小部件内

import 'package:flutter/material.dart';

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

/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        // notice "hot reload" button
        primarySwatch: Colors.blue,
      ),
      home: GetPosition(),
    );
  }
}

class GetPosition extends StatefulWidget {
  String changeText =
      'dynamicaly changing text dynamicaly changing text dynamicaly changing text dynamicaly changing text dynamicaly changing text dynamicaly changing text';
  @override
  _GetPositionState createState() => _GetPositionState();
}

class _GetPositionState extends State<GetPosition> {
  GlobalKey _key = GlobalKey();
  double _x = 0, _y = 0;

  // this function is trigger when the user presses the floating button
  void _getOffset(GlobalKey key) {
    RenderBox? box = key.currentContext!.findRenderObject() as RenderBox?;
    Offset position = box!.localToGlobal(Offset.zero);
    setState(() {
      _x = position.dx;
      _y = position.dy;
    });
  }

  @override
  Widget build(BuildContext context) {
    final List<String> entries = <String>[
      _x != null ? "X: ${_x.toInt()}" : '',
      _y != null ? "Y: $_y" : '',
      _x != null ? 'Entry A' : '',
      _x != null ? 'Entry B' : '',
      _x != null ? 'EntryC' : ''
    ];
    return Scaffold(
      body: Stack(children: [
        RichText(
          textAlign: TextAlign.left,
          text: TextSpan(
            text: '${widget.changeText}',
            style: TextStyle(color: Colors.black, fontSize: 18.0),
            children: [
              WidgetSpan(
                child: InkWell(
                  splashFactory: NoSplash.splashFactory,
                  key: _key,
                  onTap: () {},
                  child: Text(
                    " ListView.builder",
                    style: TextStyle(color: Colors.red, fontSize: 18.0),
                  ),
                ),
              ),
              TextSpan(
                text: '${widget.changeText}',
                style: TextStyle(color: Colors.black, fontSize: 18.0),
              ),
            ],
          ),
        ),
        Positioned(
          top: _y + 10,
          left: _x,
          child: SizedBox(
            width: 310,
            height: 200,
            child: Builder(builder: (context) {
              return ListView.builder(
                  padding: EdgeInsets.all(0.0),
                  itemCount: entries.length,
                  itemBuilder: (BuildContext context, int index) {
                    return ListTile(
                      dense: true,
                      // height: 300,
                      // color: Colors.amber[colorCodes[index]],
                      title: Text(
                        '${entries[index]}',
                        style: TextStyle(color: Colors.red, fontSize: 18.0),
                      ),
                    );
                  });
            }),
          ),
        ),
        Row(children: [
          ElevatedButton(
              onPressed: () {
                // randomPosition();

                _getOffset(_key);
                widget.changeText = widget.changeText + ' add text  dsds';
                // print(randomLeft);
                // print(randomTop);
                setState(() {});
              },
              child: Text('Add some text')),
          ElevatedButton(
            onPressed: () {
              _getOffset(_key);
              if (widget.changeText.length > 10) {
                widget.changeText = widget.changeText
                    .substring(10, widget.changeText.length - 1);
              } else {
                if (widget.changeText.length > 0) {
                  widget.changeText = widget.changeText
                      .substring(0, widget.changeText.length - 1);
                } else {}
              }

              setState(() {});
            },
            child: const Text('Delete some Text'),
          )
        ]),
      ]),
      floatingActionButton: FloatingActionButton(
          onPressed: () {
            // randomPosition();

            _getOffset(_key);
            widget.changeText = widget.changeText + ' add text  dsds';
            // print(randomLeft);
            // print(randomTop);
            setState(() {});
          },
          child: Icon(Icons.calculate)),
    );
  }
}

需要将“clipBehavior: Clip.none”添加到 Stack 小部件以在 Stack 小部件之外显示定位小部件

Stack(clipBehavior: Clip.none, children: [
                  RichText(
                    textAlign: TextAlign.left,
                    text: TextSpan(
                      text: '${widget.changeText}',
                      style: TextStyle(color: Colors.black, fontSize: 18.0),
                      children: [
                        WidgetSpan(
                          child: InkWell(
                            splashFactory: NoSplash.splashFactory,
                            key: _key,
                            onTap: () {},
                            child: Text(
                              " ListView.builder",
                              style:
                                  TextStyle(color: Colors.red, fontSize: 18.0),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Positioned(
                    top: _y + 40,
                    left: _x + 50,
                    child: Container(
                      width: 200,
                      height: 200,
                      child: Builder(builder: (context) {
                        return ListView.builder(
                            padding: EdgeInsets.all(0.0),
                            itemCount: entries.length,
                            itemBuilder: (BuildContext context, int index) {
                              return Container(
                                color: Colors.amber[colorCodes[index]],
                                child:
                                    // dense: true,
                                    // height: 300,

                                    // children: [
                                    Text(
                                  '${entries[index]}',
                                  style: TextStyle(
                                      color: Colors.red, fontSize: 18.0),
                                ),
                                // ],
                              );
                            });
                      }),
                    ),
                  ),
                  Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        ElevatedButton(
                            onPressed: () {
                              // randomPosition();
                              print(screenWidth);
                              _getOffset(_key);
                              widget.changeText = widget.changeText +
                                  ' dynamic text added dynamic text added dynamic text added dynamic text added dynamic text added dynamic text added';
                              // print(randomLeft);
                              // print(randomTop);
                              setState(() {});
                            },
                            child: Text('Add some text')),
                        ElevatedButton(
                          onPressed: () {
                            print(screenWidth);
                            _getOffset(_key);
                            if (widget.changeText.length > 25) {
                              widget.changeText = widget.changeText
                                  .substring(25, widget.changeText.length - 1);
                            } else {
                              if (widget.changeText.length > 0) {
                                widget.changeText = widget.changeText
                                    .substring(0, widget.changeText.length - 1);
                              } else {}
                            }

                            setState(() {});
                          },
                          child: const Text('Delete some Text'),
                        )
                      ]),
                ]),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM