草庐IT

dart - 在 Flutter 中添加大小的 PageView 的正确方法是什么?

coder 2023-07-22 原文

我尝试添加一个 PageView它没有填满整个屏幕。

为此,我将 PageView 放在 Column 中:

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      body: new Column(
        children: <Widget>[
          new SizedBox(height: 100.0, child: new Center(child: new Text("sticky header"))),
          new Expanded(
            child: new PageView(
              children: <Widget>[
                new Container(
                  color: Colors.red,
                  child: new Padding(
                    padding: const EdgeInsets.all(50.0),
                    child: new _Painter(),
                  ),
                ),
                new Container(
                  color: Colors.green,
                  child: new Padding(
                    padding: const EdgeInsets.all(50.0),
                    child: new _Painter(),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

到目前为止这有效。

每个 PageView 都有一个 _Painter它有一个 RenderBox画一些东西。

我的问题来了:我使用 handleEvent检测拖动事件的方法,但 y 位置错误。你可以看到绘制的线不是我触摸屏幕的地方(透明气泡)。

我该如何解决这个问题?我必须自己计算正确的 y 位置吗?

您可以找到 full source here .

更新

globalToLocal 中途解决了问题,但我仍然必须在计算中包括填充。有没有办法获取小部件的填充?

void _handleDragUpdate(DragUpdateDetails details) {
  final pos = globalToLocal(details.globalPosition);
  _currentPath?.lineTo(pos.dx + 50.0, pos.dy + 50.0);
  markNeedsPaint();
}

奖励积分

当我左右拖动 PageView 时,我的 _PainterRenderBox 忘记了绘制的线条。记住这些台词的最佳位置在哪里?将它们存储在 _Painter_MyHomePageState 中?

最佳答案

您缺少的是关于 RenderBoxglobalPosition 转换为 localPosition。你可以像这样实现它

// onDragUpdate with the Painting Context
RenderBox referenceBox = context.findRenderObject();
Offset localPosition = referenceBox.globalToLocal(details.globalPosition);
// then use the localPosition to draw

您的用例的用法示例,如 here :

class _PainterRenderBox extends RenderBox {
  final _lines = new List<Path>();
  PanGestureRecognizer _drag;
  Path _currentPath;

  // variable to store padding
  Offset padding;

  _PainterRenderBox() {
    final GestureArenaTeam team = new GestureArenaTeam();
    _drag = new PanGestureRecognizer()
      ..team = team
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
      ..onEnd = _handleDragEnd;
  }

  @override
  bool get sizedByParent => true;

  @override
  bool hitTestSelf(Offset position) => true;

  @override
  handleEvent(PointerEvent event, BoxHitTestEntry entry) {
    assert(debugHandleEvent(event, entry));
    if (event is PointerDownEvent) {
      _drag.addPointer(event);
    }
  }

  @override
  paint(PaintingContext context, Offset offset) {
    final Canvas canvas = context.canvas;

    // update padding
    padding = offset;

    final Paint paintBorder = new Paint()
      ..strokeWidth = 1.0
      ..style = PaintingStyle.stroke
      ..color = Colors.white.withAlpha(128);
    canvas.drawRect(offset & size, paintBorder);

    final Paint paintPath = new Paint()
      ..strokeWidth = 5.0
      ..style = PaintingStyle.stroke
      ..color = Colors.white;
    _lines.forEach((path) {
      canvas.drawPath(path, paintPath);
    });
  }

  // check if the point lies inside drawable area
  bool _canDraw(Offset offset){
    return (padding & size).contains(offset);
  }

  void _handleDragStart(DragStartDetails details) {
    _currentPath = new Path();
    Offset point = globalToLocal(details.globalPosition); // convert globalPosition to localPosition
    point = padding + point; // add the padding to localPosition if any
    // check if point lies inside drawable area and then markNeedsPaint
    if(_canDraw(point)){
      _currentPath?.moveTo(point.dx, point.dy);
      _lines.add(_currentPath);
      markNeedsPaint();
    }
  }

  void _handleDragUpdate(DragUpdateDetails details) {
    Offset point = globalToLocal(details.globalPosition); // convert globalPosition to localPosition
    point = padding + point; // add the padding to localPosition if any
    // check if point lies inside drawable area and then markNeedsPaint
    if(_canDraw(point)){
      _currentPath?.lineTo(point.dx, point.dy);
      markNeedsPaint();
    }
  }

  void _handleDragEnd(DragEndDetails details) {
    _currentPath = null;
    markNeedsPaint();
  }
}

有一个类似用例的问题允许用户在屏幕上签名。希望这可以帮助您了解如何跟踪路径。可以看看here .

希望对您有所帮助!

关于dart - 在 Flutter 中添加大小的 PageView 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49320015/

有关dart - 在 Flutter 中添加大小的 PageView 的正确方法是什么?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  5. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  6. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  7. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  8. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  9. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  10. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

随机推荐