在未渲染时获取小部件的大小/位置的最佳方法 [英] Flutter best way to get size/position of widget when it doesn't render

查看:77
本文介绍了在未渲染时获取小部件的大小/位置的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如何获取小部件的大小/位置.但是问题是,如果我们要获取在 FutureBuilder 成功后将显示的窗口小部件的大小/位置,那我们如何获得?

更清楚:

我在窗口小部件的层次结构下面.

  • CustomScrollView
    • SliverAppBar
    • SliverToBoxAdapter
      • SingleChildScrollView
        • 容器 //涵盖了完整的Scree
        • 按钮
          ||<-基于按钮单击 *//我自己的代码*
          容器
          子〜>空 OR FutureBuilder *//我自己的代码*

FutureBuilder 涵盖在 Container 小部件下.我想得到此容器小部件的大小/位置.

我做到了,但方法不正确.

  child:FutureBuilder< MealModelData>(未来:_futureForMealList,建造者:(BuildContext上下文,AsyncSnapshot< MealModelData>快照){如果(snapshot.data!= null){MealModelData mealMdl =快照.数据;列表< MealList>进餐清单= meatMdl.mealList;如果(mealMdl!= null)返回ListView.builder(物理:NeverScrollableScrollPhysics(),rinkWrap:是的,itemCount:mealList.length,itemBuilder:(BuildContext上下文,整数索引){如果(index == mealList.length-1&!isGotPos {isGotPos = true;_callBackForGetTopPosition();}........... 

方法代码为:

  _callBackForGetTopPosition(){WidgetsBinding.instance.addPostFrameCallback((_){最终的RenderBox renderBoxRed =_keyForListView.currentContext.findRenderObject();最终positionRed = renderBoxRed.localToGlobal(Offset.zero);print('X = $ {positionRed.dx}和Y = $ {positionRed.dy}')});} 

我找到了这个

日志

  I/flutter(26712):最大高度:40.0,最大宽度:40.0I/颤振(26712):最大高度:60.0,最大宽度:60.0I/颤振(26712):最大高度:80.0,最大宽度:80.0I/颤振(26712):最大高度:100.0,最大宽度:100.0 

I know, How to get size/position of the widget. But question is If we want to get size/position of widget that will be shown after success of FutureBuilder then how can we get?

For more clear:

I have below hierarchy of the widget.

  • CustomScrollView
    • SliverAppBar
    • SliverToBoxAdapter
      • SingleChildScrollView
        • Column
        • Container // Covered full Scree
        • Button
          || <-- based on button Click *//My own code*
          Container
          Child ~> null OR FutureBuilder *//My own code*

This FutureBuilder covered under Container widget. And I want to get size/position of this Container widget.

I did it but not proper way.

child: FutureBuilder<MealModelData>(
          future: _futureForMealList,
          builder:
              (BuildContext context, AsyncSnapshot<MealModelData> snapshot) {

                if (snapshot.data != null) {
                  MealModelData mealMdl = snapshot.data;
                  List<MealList> mealList = mealMdl.mealList;

                  if (mealMdl != null)
                    return ListView.builder(
                      physics: NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemCount: mealList.length,
                      itemBuilder: (BuildContext context, int index) {

                        if (index == mealList.length - 1 && !isGotPos{
                          isGotPos= true;
                          _callBackForGetTopPosition();
                        }

                       .
                       .                       .
                       .                       .
                       .                       .
                       .                       .
                       .                       .

And method code is:

_callBackForGetTopPosition() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final RenderBox renderBoxRed =
          _keyForListView.currentContext.findRenderObject();
      final positionRed = renderBoxRed.localToGlobal(Offset.zero);
      print('X = ${positionRed.dx} and Y = ${positionRed.dy}')

    });
  }             

I found this one How to get a height of a Widget?

But can't able to declare SchedulerBinding.instance.....

解决方案

You can use LayoutBuilder to determine the widget's size. Here's a sample to demonstrate how the widget works.

One of the use case of the LayoutBuilder widget is determining the dimension of where widgets can be displayed and adapt their size to it.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  var dimension = 40.0;

  increaseWidgetSize() {
    setState(() {
      dimension += 20;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(children: <Widget>[
          Text('Dimension: $dimension'),
          Container(
            color: Colors.teal,
            alignment: Alignment.center,
            height: dimension,
            width: dimension,
            // LayoutBuilder inherits its parent widget's dimension. In this case, the Container in teal
            child: LayoutBuilder(builder: (context, constraints) {
              debugPrint('Max height: ${constraints.maxHeight}, max width: ${constraints.maxWidth}');
              return Container(); // create function here to adapt to the parent widget's constraints
            }),
          ),
        ]),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: increaseWidgetSize,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Demo

Logs

I/flutter (26712): Max height: 40.0, max width: 40.0
I/flutter (26712): Max height: 60.0, max width: 60.0
I/flutter (26712): Max height: 80.0, max width: 80.0
I/flutter (26712): Max height: 100.0, max width: 100.0

这篇关于在未渲染时获取小部件的大小/位置的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆