【发布时间】:2021-07-18 03:21:49
【问题描述】:
当孩子的尺寸小于屏幕尺寸时,使用 Stack 很容易控制布局。但是当孩子的身高大于屏幕尺寸时,就需要使用SingleChildScrollView。但是如果我使用它,整个屏幕会变白并产生如下所示的错误。
在这些情况下使用Stack 和SingleChildScrollView 时如何处理布局。
任何帮助是极大的赞赏。谢谢。
示例代码
import 'package:flutter/material.dart';
void main(List<String> args) {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: SingleChildScrollView(
child: Stack(
fit: StackFit.expand,
children: [
_Background(),
Positioned(left: 0, top: 100, child: WidgetA()),
Positioned(left: 0, top: 270, child: WidgetB()),
],
),
),
),
),
);
}
}
class _Background extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
);
}
}
class WidgetA extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: randomHeight(),
width: MediaQuery.of(context).size.width,
color: Colors.purple,
child: Center(
child: Text('Widget A'),
),
);
}
}
class WidgetB extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: 250,
width: MediaQuery.of(context).size.width,
color: Colors.yellow,
child: Center(
child: Text('Widget B'),
),
);
}
}
错误
════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderRepaintBoundary#2e73f relayoutBoundary=up1 NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1940 pos 12: 'hasSize'
The relevant error-causing widget was
Scaffold
lib/main.dart:11
════════════════════════════════════════════════════════════════════════════════
【问题讨论】: