【问题标题】:Error: BoxConstraints forces an infinite height错误:BoxConstraints 强制无限高
【发布时间】:2021-07-22 04:14:04
【问题描述】:

当我尝试从主页移动到产品页面时引发以下异常。我猜是因为使用了列表视图而引发了异常。你能帮我找到正确的使用方法吗?

它应该看起来像这样:

但相反,它向我显示错误

======== 渲染库捕获的异常 ==================================================== === 在 performLayout() 期间引发了以下断言: BoxConstraints 强制无限高。

    These invalid constraints were provided to RenderDecoratedBox's layout() function by the following function, which probably computed the invalid constraints in question:
      RenderConstrainedBox.performLayout (package:flutter/src/rendering/proxy_box.dart:277:14)
    The offending constraints were: BoxConstraints(w=263.7, h=Infinity)
    The relevant error-causing widget was: 
      Container file:///C:/Users/bhask/Downloads/your_store/lib/screens/product_page.dart:143:36
    When the exception was thrown, this was the stack: 
    #0      BoxConstraints.debugAssertIsValid.<anonymous closure>.throwError (package:flutter/src/rendering/box.dart:517:9)
    #1      BoxConstraints.debugAssertIsValid.<anonymous closure> (package:flutter/src/rendering/box.dart:561:21)
    #2      BoxConstraints.debugAssertIsValid (package:flutter/src/rendering/box.dart:565:6)
    #3      RenderObject.layout (package:flutter/src/rendering/object.dart:1679:24)
    #4      RenderConstrainedBox.performLayout (package:flutter/src/rendering/proxy_box.dart:277:14)
    ...
    The following RenderObject was being processed when the exception was fired: RenderConstrainedBox#cef26 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...  parentData: offset=Offset(0.0, 0.0) (can use size)
    ...  constraints: BoxConstraints(w=263.7, 0.0<=h<=Infinity)
    ...  size: MISSING
    ...  additionalConstraints: BoxConstraints(w=65.0, h=Infinity)
    RenderObject: RenderConstrainedBox#cef26 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
      parentData: offset=Offset(0.0, 0.0) (can use size)
      constraints: BoxConstraints(w=263.7, 0.0<=h<=Infinity)
      size: MISSING
      additionalConstraints: BoxConstraints(w=65.0, h=Infinity)
    ...  child: RenderDecoratedBox#003df NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...    parentData: <none>
    ...    constraints: MISSING
    ...    size: MISSING
    ...    decoration: BoxDecoration
    ...      color: Color(0xff000000)
    ...      borderRadius: BorderRadius.circular(12.0)
    ...    configuration: ImageConfiguration(bundle: PlatformAssetBundle#dc45b(), devicePixelRatio: 2.8, locale: en_US, textDirection: TextDirection.ltr, platform: android)
    ...    child: RenderParagraph#fda35 NEEDS-LAYOUT NEEDS-PAINT
    ...      parentData: <none>
    ...      constraints: MISSING
    ...      size: MISSING
    ...      textAlign: start
    ...      textDirection: ltr
    ...      softWrap: wrapping at box width
    ...      overflow: clip
    ...      locale: en_US
    ...      maxLines: unlimited
    ...      text: TextSpan
    ...        debugLabel: ((((englishLike body1 2014).merge(blackMountainView bodyText2)).copyWith).copyWith).merge(unknown)
    ...        inherit: false
    ...        color: Color(0xffffffff)
    ...        family: Poppins_regular
    ...        familyFallback: Poppins
    ...        size: 16.0
    ...        weight: 600
    ...        baseline: alphabetic
    ...        decoration: TextDecoration.none
    ...        "Add To Cart"
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    The following assertion was thrown during performLayout():
    RenderBox was not laid out: RenderConstrainedBox#cef26 relayoutBoundary=up10 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1930 pos 12: 'hasSize'
    
    
    Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
    In either case, please report this assertion by filing a bug on GitHub:
      https://github.com/flutter/flutter/issues/new?template=2_bug.md
    
    The relevant error-causing widget was: 
      Container file:///C:/Users/bhask/Downloads/your_store/lib/screens/product_page.dart:143:36
    When the exception was thrown, this was the stack: 
    #2      RenderBox.size (package:flutter/src/rendering/box.dart:1930:12)
    #3      RenderPadding.performLayout (package:flutter/src/rendering/shifted_box.dart:237:39)
    #4      RenderObject.layout (package:flutter/src/rendering/object.dart:1779:7)
    #5      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
    #6      RenderObject.layout (package:flutter/src/rendering/object.dart:1779:7)
    ...
    The following RenderObject was being processed when the exception was fired: RenderPadding#107a1 relayoutBoundary=up9 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...  parentData: <none> (can use size)
    ...  constraints: BoxConstraints(w=279.7, 0.0<=h<=Infinity)
    ...  size: MISSING
    ...  padding: EdgeInsets(16.0, 0.0, 0.0, 0.0)
    ...  textDirection: ltr
    RenderObject: RenderPadding#107a1 relayoutBoundary=up9 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
      parentData: <none> (can use size)
      constraints: BoxConstraints(w=279.7, 0.0<=h<=Infinity)
      size: MISSING
      padding: EdgeInsets(16.0, 0.0, 0.0, 0.0)
      textDirection: ltr
    ...  child: RenderConstrainedBox#cef26 relayoutBoundary=up10 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...    parentData: offset=Offset(16.0, 0.0) (can use size)
    ...    constraints: BoxConstraints(w=263.7, 0.0<=h<=Infinity)
    ...    size: MISSING
    ...    additionalConstraints: BoxConstraints(w=65.0, h=Infinity)
    ...    child: RenderDecoratedBox#003df NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...      parentData: <none>
    ...      constraints: MISSING
    ...      size: MISSING
    ...      decoration: BoxDecoration
    ...        color: Color(0xff000000)
    ...        borderRadius: BorderRadius.circular(12.0)
    ...      configuration: ImageConfiguration(bundle: PlatformAssetBundle#dc45b(), devicePixelRatio: 2.8, locale: en_US, textDirection: TextDirection.ltr, platform: android)
    ...      child: RenderParagraph#fda35 NEEDS-LAYOUT NEEDS-PAINT
    ...        parentData: <none>
    ...        constraints: MISSING
    ...        size: MISSING
    ...        textAlign: start
    ...        textDirection: ltr
    ...        softWrap: wrapping at box width
    ...        overflow: clip
    ...        locale: en_US
    ...        maxLines: unlimited
    ...        text: TextSpan
    ...          debugLabel: ((((englishLike body1 2014).merge(blackMountainView bodyText2)).copyWith).copyWith).merge(unknown)
    ...          inherit: false
    ...          color: Color(0xffffffff)
    ...          family: Poppins_regular
    ...          familyFallback: Poppins
    ...          size: 16.0
    ...          weight: 600
    ...          baseline: alphabetic
    ...          decoration: TextDecoration.none
    ...          "Add To Cart"
    ====================================================================================================

这是我的产品页面代码:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:your_store/constants.dart';
import 'package:your_store/services/firebase_services.dart';
import 'package:your_store/widgets/custom_action_bar.dart';
import 'package:your_store/widgets/image_swipe.dart';
import 'package:your_store/widgets/product_size.dart';

class ProductPage extends StatefulWidget {
  final String? productId;
  ProductPage({this.productId});

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

class _ProductPageState extends State<ProductPage> {

  FirebaseServices _firebaseServices = FirebaseServices();

  String? _selectedProductSize = "0";

  Future _addToCart() {
    return _firebaseServices.usersRef
        .doc(_firebaseServices.getUserId())
        .collection("Cart")
        .doc(widget.productId)
        .set({"size": _selectedProductSize});
  }

  final SnackBar _snackBar = SnackBar(content: Text("Product added to the cart."),);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      children: [
        FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          future: _firebaseServices.productRef.doc(widget.productId).get(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Scaffold(
                body: Center(
                  child: Text("Error: ${snapshot.error}"),
                ),
              );
            }

            if (snapshot.connectionState == ConnectionState.done) {
              //Firebase document data map
             final documentData = snapshot.data!.data()!;

              //List of images
              List imageList = documentData["images"];
              List productSize = documentData["size"];

              //Set an initial size
              _selectedProductSize = productSize[0];

              return ListView(
                padding: EdgeInsets.all(0),
                children: [
                  ImageSwipe(
                    imageList: imageList,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(
                      top: 24.0,
                      left: 24.0,
                      right: 24.0,
                      bottom: 4.0,
                    ),
                    child: Text(
                      documentData["name"] ?? "",
                      style: Constants.boldHeading,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(
                      vertical: 4.0,
                      horizontal: 24.0,
                    ),
                    child: Text(
                      documentData["price"] ?? "",
                      style: TextStyle(
                        fontSize: 18.0,
                        color: Theme.of(context).accentColor,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(
                      vertical: 8.0,
                      horizontal: 24.0,
                    ),
                    child: Text(
                      documentData["desc"] ?? "",
                      style: TextStyle(fontSize: 16.0),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(
                      vertical: 24.0,
                      horizontal: 24.0,
                    ),
                    child: Text(
                      "Select Size",
                      style: Constants.regularDarkText,
                    ),
                  ),
                  ProductSize(
                    productSize: productSize,
                    onSelected: (size){
                      _selectedProductSize = size;
                    },
                  ),
                  Padding(
                    padding: const EdgeInsets.all(24.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          width: 65.0,
                          height: 65.0,
                          decoration: BoxDecoration(
                            color: Color(0xFFDCDCDC),
                            borderRadius: BorderRadius.circular(12.0),
                          ),
                          alignment: Alignment.center,
                          child: Image(
                            image: AssetImage("assets/images/tab_saved.png"),
                            height: 22.0,
                          ),
                        ),
                        Expanded(
                          child: GestureDetector(
                            onTap: () async {
                              await _addToCart();
                              ScaffoldMessenger.of(context).showSnackBar(_snackBar);
                            },
                            child: Container(
                              width: 65.0,
                              margin: EdgeInsets.only(
                                left: 16.0,
                              ),
                              height: double.infinity,
                              decoration: BoxDecoration(
                                  color: Colors.black,
                                  borderRadius: BorderRadius.circular(12.0)),
                              child: Text(
                                "Add To Cart",
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16.0,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              );
            }

            //Loading State
            return Scaffold(
              body: Center(
                child: CircularProgressIndicator(),
              ),
            );
          },
        ),
        CustomActionBar(
          hasBackArrow: true,
          hasTitle: false,
          hasBackground: false,
        ),
      ],
    ));
  }
}

【问题讨论】:

  • 也许堆栈内的列表视图给出了一些奇怪的尺寸,尝试使用参数 fit: Stackfit.passthrough 或者你可能根本不需要那个堆栈,并且可以使用你的 futurebuilder 作为 body 和底部导航栏中的 CustomActionBar
  • 对不起,我没明白。请你实现它并给我看一次好吗。

标签: android flutter dart flutter-layout flutter-dependencies


【解决方案1】:

2 个选项

body: Stack(
  fit: Stackfit.passthrough,
  children: [
    .... //same code
  ],
),

return Scaffold(
   body: FutureBuilder(
      .... ///same code
   ),
   bottomNavigationBar: CustomActionBar(
          hasBackArrow: true,
          hasTitle: false,
          hasBackground: false,
        ),
 );

另外作为旁注,这个脚手架是不必要的

  return Scaffold( /// You can remove the scaffold and keep just Center(child: CircularProgressIndicator(),)
    body: Center(
       child: CircularProgressIndicator(),
    ),
  );

Stack 没有给孩子一个执行的大小,所以 ListView 尝试一个无限的无限大小来执行它的构建方法

【讨论】:

  • 谢谢,但我不知道为什么它不适合我。错误始终存在。我想如果你看看我的代码,它可能会对你有更好的帮助。我想我不能很好地表达自己。这是代码链接。 github.com/Bhaskar2510/Final。当您登录并选择产品时,如果我尝试搜索某些内容,甚至在搜索页面上,问题就开始了。
【解决方案2】:

问题在于您的Expanded 小部件。首先,您不应该在ListView 中包含Expanded,除非Expanded 是具有定义高度的东西的孩子,而您的高度不是。此外,您的 ListView 甚至不是具有已定义高度的 Widget 的孩子。 Widget 树中的任何内容都不知道它应该有多高。您需要为ListView 的所有子项设置高度,尤其是Expanded 小部件。 Padding 小部件没有高度,Row 小部件也没有。您需要将 Expanded 的直系父母之一包裹在 Container 或具有指定高度的东西中,否则它将在 ListView 内永远扩展并给您 infinite height 错误。

旁注:您将Expanded 的孩子的高度设置为double.infinity,这是不必要的。

编辑:

这个错误代码:

ListView(
  //...
  children: [
    //...
    Padding(
      //...
      child: Row(
        children: [
          //...
          Expanded(
            child: Container(
              //...
              height: double.infinity,
              child: Text('text'),
            ),
          ),
        ],
      ),
    ),
  ],
);

必须变成这样:

ListView(
  //...
  children: [
    //...
    Container(
      height: 100.0, //or whatever you want
      width: 400.0, //or whatever you want
      padding: EdgeInsets.all(24.0),
      //...
      child: Row(
        children: [
          //...
          Expanded(
            child: Container(
              //...
              child: Text('text'),
            ),
          ),
        ],
      ),
    ),
  ],
);

这是因为Expanded 向上搜索小部件树,寻找告诉它允许大小的父级。您没有提供这样的父母,这会导致您的错误消息。现在,这可能无法完全解决您的问题,因为您的 ListView 中可能还有其他元素具有未定义的高度。这些也会导致错误,因为ListView 小部件的高度基于其子级高度的总和。如果ListView 不知道它的每个孩子有多高,那么它就无法知道它应该有多高,并且您再次收到该错误消息。

总之,您需要注意两件事(不仅在这里,而且总是):

  1. 所有Expanded 小部件都有定义高度的父级
  2. ListView 小部件的所有子级都已定义高度

碰巧您可以通过将 Padding 小部件更改为大小为 Container 的小部件来解决这两个问题。

【讨论】:

  • 嘿!如果您可以通过在我的代码中实现更改来举例说明并帮助我,我已经更新了我的问题。
  • 谢谢兄弟,现在一切正常了。
  • 酷。乐于助人
【解决方案3】:

请添加ListView的shrinkWrap true。

return ListView(
       shrinkWrap: true,
       padding: EdgeInsets.all(0),
       children: [
         ImageSwipe(
           imageList: imageList,
         ),
         Padding(
           padding: const EdgeInsets.only(
             top: 24.0,
             left: 24.0,
             right: 24.0,
             bottom: 4.0,
           ),
           child: Text(
             documentData["name"] ?? "",
             style: Constants.boldHeading,
           ),
         ),
         Padding(
           padding: const EdgeInsets.symmetric(
             vertical: 4.0,
             horizontal: 24.0,
           ),
           child: Text(
             documentData["price"] ?? "",
             style: TextStyle(
               fontSize: 18.0,
               color: Theme.of(context).accentColor,
               fontWeight: FontWeight.w600,
             ),
           ),
         ),
         Padding(
           padding: const EdgeInsets.symmetric(
             vertical: 8.0,
             horizontal: 24.0,
           ),
           child: Text(
             documentData["desc"] ?? "",
             style: TextStyle(fontSize: 16.0),
           ),
         ),
         Padding(
           padding: const EdgeInsets.symmetric(
             vertical: 24.0,
             horizontal: 24.0,
           ),
           child: Text(
             "Select Size",
             style: Constants.regularDarkText,
           ),
         ),
         ProductSize(
           productSize: productSize,
           onSelected: (size){
             _selectedProductSize = size;
           },
         ),
         Padding(
           padding: const EdgeInsets.all(24.0),
           child: Row(
             mainAxisAlignment: MainAxisAlignment.start,
             children: [
               Container(
                 width: 65.0,
                 height: 65.0,
                 decoration: BoxDecoration(
                   color: Color(0xFFDCDCDC),
                   borderRadius: BorderRadius.circular(12.0),
                 ),
                 alignment: Alignment.center,
                 child: Image(
                   image: AssetImage("assets/images/tab_saved.png"),
                   height: 22.0,
                 ),
               ),
               Expanded(
                 child: GestureDetector(
                   onTap: () async {
                     await _addToCart();
                     ScaffoldMessenger.of(context).showSnackBar(_snackBar);
                   },
                   child: Container(
                     width: 65.0,
                     margin: EdgeInsets.only(
                       left: 16.0,
                     ),
                     height: double.infinity,
                     decoration: BoxDecoration(
                         color: Colors.black,
                         borderRadius: BorderRadius.circular(12.0)),
                     child: Text(
                       "Add To Cart",
                       style: TextStyle(
                         color: Colors.white,
                         fontSize: 16.0,
                         fontWeight: FontWeight.w600,
                       ),
                     ),
                   ),
                 ),
               ),
             ],
           ),
         ),
       ],
     );

【讨论】:

  • 它没有改变任何问题仍然和以前一样。
  • 能否请您将 Listview 替换为 Column 并添加 mainAxisSize: MainAxisSize.min。我希望它对你有用。
  • 我尝试在传递 mainAxisSize 的第 n 列中包装列表视图,但错误仍然保持不变。
  • 不换行用 Column 换行,用 SingleChildScrollView 换行。
  • 谢谢,但我不知道为什么它不适合我。错误始终存在。我想如果你看看我的代码,它可能会对你有更好的帮助。我想我不能很好地表达自己。这是代码链接github.com/Bhaskar2510/Final。当您登录并选择产品时,如果我尝试搜索某些内容,甚至在搜索页面上,问题就开始了。
猜你喜欢
  • 2022-01-04
  • 2021-10-15
  • 2020-12-22
  • 2023-04-09
  • 2020-04-27
  • 2019-11-04
  • 2019-12-02
  • 2019-02-25
  • 2020-09-21
相关资源
最近更新 更多