将width
类的container
中提取的constraints.biggest
赋予LayoutBuilder
时,出现错误。我制作了一个ResponsiveSafeArea
类,其中LayoutBuilder
包裹在SafeArea
周围,以便在需要时使用它
════════ Exception caught by rendering library ═════════════════════════════════
BoxConstraints forces an infinite width.
下面是代码
class HomePage extends StatelessWidget {
static List foodItemInfoList = [ ... ];
ScrollController _scrollController = new ScrollController();
@override
Widget build(BuildContext context) {
return ResponsiveSafeArea(
builder: (context, widgetSize ) =>
Stack(
fit: StackFit.loose,
children: <Widget>[
CustomScrollView(
controller: _scrollController,
slivers: <Widget>[
SliverPersistentHeader( ... ),
SliverToBoxAdapter(
child: Column(
children: <Widget>[
Container( ... ),
/// ~~~~~~~~~~~~~~~~ BELOW CONTAINER IS CULPRIT
Container(
height: widgetSize.height * 0.12,
color: Colors.pink,
child: FoodCategorySlider(),
),
],
),
),
],
),
],
),
}
}
class FoodCategorysectionItem extends StatelessWidget {
FoodCategorysectionItem(this.foodCtgItem);
final Map foodCtgItem;
@override
Widget build(BuildContext context) {
return ResponsiveSafeArea(
builder: (context, widgetSize) => Container(
color: Colors.orange,
width: widgetSize.width * 0.4, // ---------------------------- HERE GIVING WIDTH GIVEs ERROR
),
);
}
}
class FoodCategorySlider extends StatelessWidget {
// List for testing
static List FoodCatgSectionItemList = [ ... ];
@override
Widget build(BuildContext context) {
return ResponsiveSafeArea(
builder: (context, widgetSize) => Container(
height: widgetSize.height,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: FoodCatgSectionItemList.length,
itemBuilder: (context, index) {
return FoodCategorysectionItem(FoodCatgSectionItemList[index]);
},
),
),
);
}
}
import 'package:flutter/material.dart';
typedef ResponsiveBuilder = Widget Function(
BuildContext context,
Size,
);
class ResponsiveSafeArea extends StatelessWidget {
final ResponsiveBuilder responsiveBuilder;
const ResponsiveSafeArea({
Key key,
@required ResponsiveBuilder builder,
}) : responsiveBuilder = builder,
super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
return responsiveBuilder(
context,
constraints.biggest,
);
},
),
);
}
}