【发布时间】:2022-01-18 13:03:27
【问题描述】:
你能捕捉到在布局 Widget 时 Flutter 中抛出的异常吗,就像在下面的示例中尝试的那样,它不起作用?
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: 'Test',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
body: _offendingTestBody(),
);
}
Widget _offendingTestBody() {
return SafeArea(
child: SizedBox(
height: 300,
child: Container(
color: Colors.green,
child: _columnOrListView(List.filled(22, Text("test")))),
),
);
}
Widget _columnOrListView(List<Widget> children) {
try {
return Column(
children: children,
);
} catch (e) {
return ListView(
children: children,
);
}
}
}
以下消息出现在日志中,这似乎表明渲染库 - 不必要地 - 在我的代码到达之前捕获了异常。
======== Exception caught by rendering library =====================================================
The following assertion was thrown during layout:
A RenderFlex overflowed by 74 pixels on the bottom.
The relevant error-causing widget was:
Column Column:file:///Users/user/StudioProjects/cols_try_catch/lib/main.dart:39:14
The overflowing RenderFlex has an orientation of Axis.vertical.
The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView.
The specific RenderFlex in question is: RenderFlex#74fc7 relayoutBoundary=up4 OVERFLOWING
... parentData: <none> (can use size)
... constraints: BoxConstraints(0.0<=w<=390.0, h=300.0)
... size: Size(26.0, 300.0)
... direction: vertical
... mainAxisAlignment: start
... mainAxisSize: max
... crossAxisAlignment: center
... verticalDirection: down
◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤
====================================================================================================
【问题讨论】:
标签: flutter