第一个和第二个错误与没有设置SizedBox的高度有关。虽然错误显示宽度,但这是因为它首先检查宽度,此时宽度和高度都变为0。如果在更正了这一点之后,您看到了第三个错误,我相信它与不在这里的另一段代码有关。
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Material App Bar'),
),
body: const HeroBanner(
title: "Hero Banner",
image: "assets/images/hero.png",
),
),
);
}
}
class HeroBanner extends StatelessWidget {
final String? image;
final String title;
final double maxHeight;
const HeroBanner(
{super.key, this.image, this.title = "", this.maxHeight = 100});
@override
Widget build(BuildContext context) {
return image != null
? LayoutBuilder(builder: (context, constraints) {
return ClipRect(
clipBehavior: Clip.hardEdge,
child: SizedBox(
height: maxHeight,
child: Stack(
children: [
SizedBox(
width: MediaQuery.of(context).size.width,
height: maxHeight, <----------------add height here
child: FittedBox(
fit: BoxFit.cover, child: Image.asset(image!))),
Align(
alignment: Alignment.bottomLeft,
child: Padding(
padding: comfortable,
child: Center(
child: Text(
title,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.blue, fontSize: 24),
),
),
),
),
],
),
),
);
})
: PageTitle(title);
}
}
var comfortable = const EdgeInsets.all(16);
class PageTitle extends StatelessWidget {
const PageTitle(this.title, {super.key});
final String title;
@override
Widget build(BuildContext context) {
return Text(
title,
);
}
}