Flutter如何正确地将PageView.builder放在GridView.count中?

huangapple go评论86阅读模式
英文:

Flutter how to put Pageview.builder inside GridView.count properly?

问题

我尝试使用扩展小部件和其他方法来解决这个问题,但我真的不知道如何解决这个错误...非常感谢大家的帮助👍;

这是我遇到的错误:

异常已发生。FlutterError(水平视口被赋予无限宽度。视口在滚动方向上扩展以填充其容器。在这种情况下,水平视口被赋予了无限量的水平空间来扩展。这种情况通常发生在可滚动小部件嵌套在另一个可滚动小部件内的情况下。如果此小部件始终嵌套在可滚动小部件内,就无需使用视口,因为子项始终有足够的水平空间。在这种情况下,考虑改用Row或Wrap。否则,考虑使用CustomScrollView将任意sliver连接成单个可滚动。)

网格代码:

  1. GridView.count(
  2. shrinkWrap: true,
  3. physics: const NeverScrollableScrollPhysics(),
  4. crossAxisCount: 2,
  5. padding: EdgeInsets.fromLTRB(0, 13, 0, 30),
  6. childAspectRatio: size.width / (size.height * 0.59),
  7. children: List.generate(allProducts.length, (index) {
  8. return ChangeNotifierProvider.value(
  9. value: allProducts[index],
  10. child: Container(child: const FeedsWidget()));
  11. }),
  12. ),

PageView.builder 代码:

  1. PageView.builder(
  2. scrollDirection: Axis.horizontal,
  3. itemCount: productModel.imageUrl!.length,
  4. itemBuilder: (context, index) {
  5. return ClipRRect(
  6. borderRadius: BorderRadius.circular(10),
  7. child: FancyShimmerImage(
  8. height: size.width * 0.28,
  9. width: size.width * 0.38,
  10. imageUrl: productModel.imageUrl![index],
  11. boxFit: BoxFit.fill,
  12. ),
  13. );
  14. }),

这是我的完整代码:

  1. class FeedsScreen extends StatefulWidget {
  2. static const routeName = "/FeedsScreenState";
  3. const FeedsScreen({Key? key}) : super(key: key);
  4. @override
  5. State<FeedsScreen> createState() => _FeedsScreenState();
  6. }
  7. class _FeedsScreenState extends State<FeedsScreen> {
  8. // 其他部分的代码...
  9. }
  10. class FeedsWidget extends StatefulWidget {
  11. static const routeName = "/feedItemsSc";
  12. const FeedsWidget({Key? key}) : super(key: key);
  13. @override
  14. State<FeedsWidget> createState() => _FeedsWidgetState();
  15. }
  16. class _FeedsWidgetState extends State<FeedsWidget> {
  17. // 其他部分的代码...
  18. }

希望这些信息对你有所帮助。

英文:

I tried using expanded widget and other ways to solve this but I really don't know how to solve this error.. Thank you very much for the help everyone 👍

This is the error i get :

> Exception has occurred. FlutterError (Horizontal viewport was given
> unbounded width. Viewports expand in the scrolling direction to fill
> their container. In this case, a horizontal viewport was given an
> unlimited amount of horizontal space in which to expand. This
> situation typically happens when a scrollable widget is nested inside
> another scrollable widget. If this widget is always nested in a
> scrollable widget there is no need to use a viewport because there
> will always be enough horizontal space for the children. In this case,
> consider using a Row or Wrap instead. Otherwise, consider using a
> CustomScrollView to concatenate arbitrary slivers into a single
> scrollable.)

grid code:

  1. GridView.count(
  2. shrinkWrap: true,
  3. physics: const NeverScrollableScrollPhysics(),
  4. crossAxisCount: 2,
  5. padding: EdgeInsets.fromLTRB(0, 13, 0, 30),
  6. // crossAxisSpacing: 10,
  7. childAspectRatio: size.width / (size.height * 0.59),
  8. children: List.generate(allProducts.length, (index) {
  9. return ChangeNotifierProvider.value(
  10. value: allProducts[index],
  11. child: Container(child: const FeedsWidget()));
  12. }),
  13. ),

Pageview.builder code:

  1. PageView.builder(
  2. scrollDirection: Axis.horizontal,
  3. itemCount: productModel.imageUrl!.length,
  4. itemBuilder: (context, index) {
  5. return ClipRRect(
  6. borderRadius: BorderRadius.circular(10),
  7. child: FancyShimmerImage(
  8. height: size.width * 0.28,
  9. width: size.width * 0.38,
  10. imageUrl: productModel.imageUrl![index],
  11. boxFit: BoxFit.fill,
  12. ),
  13. );
  14. }),

This is my full code:

  1. class FeedsScreen extends StatefulWidget {
  2. static const routeName = &quot;/FeedsScreenState&quot;;
  3. const FeedsScreen({Key? key}) : super(key: key);
  4. @override
  5. State&lt;FeedsScreen&gt; createState() =&gt; _FeedsScreenState();
  6. }
  7. class _FeedsScreenState extends State&lt;FeedsScreen&gt; {
  8. final TextEditingController? _searchTextController = TextEditingController();
  9. final FocusNode _searchTextFocusNode = FocusNode();
  10. @override
  11. void dispose() {
  12. _searchTextController!.dispose();
  13. _searchTextFocusNode.dispose();
  14. super.dispose();
  15. }
  16. @override
  17. void initState() {
  18. final productsProvider =
  19. Provider.of&lt;ProductsProvider&gt;(context, listen: false);
  20. productsProvider.fetchProducts();
  21. super.initState();
  22. }
  23. @override
  24. Widget build(BuildContext context) {
  25. final productsProvider = Provider.of&lt;ProductsProvider&gt;(context);
  26. List&lt;ProductModel&gt; allProducts = productsProvider.getProducts;
  27. final Color color = Utils(context).color;
  28. Size size = Utils(context).getScreenSize;
  29. return Scaffold(
  30. appBar: AppBar(
  31. leading: const BackWidget(),
  32. elevation: 0,
  33. backgroundColor: Theme.of(context).scaffoldBackgroundColor,
  34. centerTitle: true,
  35. title: vTextWidget(
  36. text: &#39;All Products&#39;,
  37. color: color,
  38. textSize: 20.0,
  39. isTitle: true,
  40. fontWeight: FontWeight.bold,
  41. ),
  42. ),
  43. body: SingleChildScrollView(
  44. child: Column(children: [
  45. Padding(
  46. padding: const EdgeInsets.all(8.0),
  47. child: SizedBox(
  48. height: kBottomNavigationBarHeight,
  49. child: TextField(
  50. focusNode: _searchTextFocusNode,
  51. controller: _searchTextController,
  52. onChanged: (valuee) {
  53. setState(() {});
  54. },
  55. decoration: InputDecoration(
  56. focusedBorder: OutlineInputBorder(
  57. borderRadius: BorderRadius.circular(12),
  58. borderSide:
  59. const BorderSide(color: Colors.greenAccent, width: 1),
  60. ),
  61. enabledBorder: OutlineInputBorder(
  62. borderRadius: BorderRadius.circular(12),
  63. borderSide:
  64. const BorderSide(color: Colors.greenAccent, width: 1),
  65. ),
  66. hintText: &quot;What&#39;s in your mind&quot;,
  67. prefixIcon: const Icon(Icons.search),
  68. suffix: IconButton(
  69. onPressed: () {
  70. _searchTextController!.clear();
  71. _searchTextFocusNode.unfocus();
  72. },
  73. icon: Icon(
  74. Icons.close,
  75. color: _searchTextFocusNode.hasFocus ? Colors.red : color,
  76. ),
  77. ),
  78. ),
  79. ),
  80. ),
  81. ),
  82. GridView.count(
  83. shrinkWrap: true,
  84. physics: const NeverScrollableScrollPhysics(),
  85. crossAxisCount: 2,
  86. padding: EdgeInsets.fromLTRB(0, 13, 0, 30),
  87. // crossAxisSpacing: 10,
  88. childAspectRatio: size.width / (size.height * 0.59),
  89. children: List.generate(allProducts.length, (index) {
  90. return ChangeNotifierProvider.value(
  91. value: allProducts[index],
  92. child: Container(child: const FeedsWidget()));
  93. }),
  94. ),
  95. ]),
  96. ),
  97. );
  98. }
  99. }

and the widget page full code:

  1. class FeedsWidget extends StatefulWidget {
  2. static const routeName = &quot;/feedItemsSc&quot;;
  3. const FeedsWidget({Key? key}) : super(key: key);
  4. @override
  5. State&lt;FeedsWidget&gt; createState() =&gt; _FeedsWidgetState();
  6. }
  7. class _FeedsWidgetState extends State&lt;FeedsWidget&gt; {
  8. final _quantityTextController = TextEditingController();
  9. @override
  10. void initState() {
  11. _quantityTextController.text = &#39;1&#39;;
  12. super.initState();
  13. }
  14. @override
  15. void dispose() {
  16. _quantityTextController.dispose();
  17. super.dispose();
  18. }
  19. @override
  20. Widget build(BuildContext context) {
  21. final themeState = Provider.of&lt;DarkThemeProvider&gt;(context);
  22. final productModel = Provider.of&lt;ProductModel&gt;(context);
  23. final cartProvider = Provider.of&lt;CartProvider&gt;(context);
  24. final wishlistProvider = Provider.of&lt;WishlistProvider&gt;(context);
  25. bool? _isInCart = cartProvider.getCartItems.containsKey(productModel.id);
  26. bool? _isInWishlist =
  27. wishlistProvider.getWishlistItems.containsKey(productModel.id);
  28. bool _isDark = themeState.getDarkTheme;
  29. final Color color = Utils(context).color;
  30. Size size = Utils(context).getScreenSize;
  31. return Padding(
  32. padding: const EdgeInsets.fromLTRB(5, 0, 8, 8),
  33. child: Material(
  34. borderRadius: BorderRadius.circular(12),
  35. color: Theme.of(context).cardColor,
  36. child: InkWell(
  37. onTap: () {
  38. Navigator.pushNamed(context, ProductDetails.routeName,
  39. arguments: productModel.id);
  40. //GlobalMethods.navigateTo(
  41. // ctx: context, routeName: ProductDetails.routeName);
  42. },
  43. borderRadius: BorderRadius.circular(12),
  44. child: Column(children: [
  45. Flexible(
  46. flex: 3,
  47. child: SizedBox(
  48. height: 300,
  49. width: 400,
  50. child: productModel.imageUrl == null
  51. ? Image(
  52. height: size.width * 0.28,
  53. width: size.width * 0.38,
  54. fit: BoxFit.fill,
  55. image:
  56. AssetImage(&#39;lib/assets/images/error_image.png&#39;),
  57. )
  58. : PageView.builder(
  59. scrollDirection: Axis.horizontal,
  60. itemCount: productModel.imageUrl!.length,
  61. itemBuilder: (context, index) {
  62. return ClipRRect(
  63. borderRadius: BorderRadius.circular(10),
  64. child: FancyShimmerImage(
  65. height: size.width * 0.28,
  66. width: size.width * 0.38,
  67. imageUrl: productModel.imageUrl![index],
  68. boxFit: BoxFit.fill,
  69. ),
  70. );
  71. }),
  72. )),
  73. //SizedBox(
  74. // height: 8,
  75. // ),
  76. // FancyShimmerImage(
  77. //imageUrl: productModel.imageUrl,
  78. // height: size.width * 0.28,
  79. // width: size.width * 0.38,
  80. // boxFit: BoxFit.fill,
  81. //),
  82. SizedBox(
  83. height: 5,
  84. ),
  85. Padding(
  86. padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
  87. child: Row(
  88. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  89. children: [
  90. Flexible(
  91. flex: 3,
  92. child: fTextWidget(
  93. text: productModel.title,
  94. maxLines: 1,
  95. color: color,
  96. textSize: 22,
  97. isTitle: true,
  98. ),
  99. ),
  100. Flexible(
  101. flex: 1,
  102. child: HeartBTN(
  103. productId: productModel.id,
  104. isInWishlist: _isInWishlist,
  105. )),
  106. ],
  107. ),
  108. ),
  109. Padding(
  110. padding: const EdgeInsets.fromLTRB(6, 8, 8, 2),
  111. child: Row(
  112. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  113. children: [
  114. Flexible(
  115. flex: 3,
  116. child: priceWidget(
  117. isDark: _isDark,
  118. salePrice: productModel.discountPrice,
  119. price: productModel.price,
  120. textPrice: _quantityTextController.text,
  121. isOneSale: productModel.isDiscounted ? true : false,
  122. ),
  123. ),
  124. // const SizedBox(
  125. // width: 10,
  126. // ),
  127. /* Flexible(
  128. child: Row(
  129. children: [
  130. FittedBox(
  131. child: fTextWidget(
  132. text: &#39;Qty&#39;,
  133. color: color,
  134. textSize: 18,
  135. isTitle: true,
  136. ),
  137. ),
  138. const SizedBox(
  139. width: 4,
  140. ),
  141. Flexible(
  142. flex: 2,
  143. child: TextFormField(
  144. controller: _quantityTextController,
  145. key: const ValueKey(&#39;10&#39;),
  146. style: TextStyle(color: color, fontSize: 17),
  147. keyboardType: TextInputType.number,
  148. maxLines: 1,
  149. decoration: InputDecoration(
  150. focusedBorder: UnderlineInputBorder(
  151. borderSide: BorderSide()),
  152. ),
  153. textAlign: TextAlign.center,
  154. cursorColor: Colors.green,
  155. enabled: true,
  156. inputFormatters: [
  157. FilteringTextInputFormatter.allow(
  158. RegExp(&#39;[0-9.,]&#39;),
  159. ),
  160. ],
  161. onChanged: (value) {
  162. setState(() {
  163. if (value.isEmpty) {
  164. _quantityTextController.text = &#39;1&#39;;
  165. } else {
  166. // total = usedPrice *
  167. // int.parse(_quantityTextController.text);
  168. }
  169. });
  170. },
  171. onSaved: (value) {},
  172. ),
  173. ),
  174. ],
  175. ),
  176. ),*/
  177. ],
  178. ),
  179. ),
  180. const Spacer(),
  181. SizedBox(
  182. width: double.infinity,
  183. child: TextButton(
  184. onPressed: _isInCart
  185. ? null
  186. : () {
  187. final User? user = authInstance.currentUser;
  188. if (user == null) {
  189. GlobalMethods.errorDialog(
  190. subtitle: &#39;Please Login&#39;,
  191. vicon: Icon(Icons.error),
  192. context: context);
  193. return;
  194. }
  195. // if (_isInCart) {
  196. // return;
  197. // }
  198. cartProvider.addProductsToCart(
  199. productId: productModel.id,
  200. quantity: int.parse(_quantityTextController.text),
  201. );
  202. },
  203. child: fTextWidget(
  204. text: _isInCart ? &#39;Added&#39; : &#39;Add to cart&#39;,
  205. maxLines: 1,
  206. color: color,
  207. textSize: 20,
  208. ),
  209. style: ButtonStyle(
  210. backgroundColor:
  211. MaterialStateProperty.all(Theme.of(context).cardColor),
  212. tapTargetSize: MaterialTapTargetSize.shrinkWrap,
  213. shape: MaterialStateProperty.all&lt;RoundedRectangleBorder&gt;(
  214. const RoundedRectangleBorder(
  215. borderRadius: BorderRadius.only(
  216. bottomLeft: Radius.circular(12.0),
  217. bottomRight: Radius.circular(12.0),
  218. ),
  219. ),
  220. )),
  221. ),
  222. ),
  223. ]),
  224. ),
  225. ),
  226. );
  227. }
  228. }

答案1

得分: 0

我已经通过添加一个具有高度和宽度的尺寸框来解决了这个问题。因此,感谢大家的帮助,问题已经解决。

以下是我的更新后的PageView.builder代码:

  1. child: SizedBox(
  2. height: 120,
  3. width: 400,
  4. child: productModel.imageUrl == null
  5. ? Image(
  6. height: size.width * 0.28,
  7. width: size.width * 0.38,
  8. fit: BoxFit.fill,
  9. image: AssetImage('lib/assets/images/error_image.png'),
  10. )
  11. : PageView.builder(
  12. scrollDirection: Axis.horizontal,
  13. itemCount: productModel.imageUrl!.length,
  14. itemBuilder: (context, index) {
  15. return ClipRRect(
  16. borderRadius: BorderRadius.circular(10),
  17. child: FancyShimmerImage(
  18. height: size.width * 0.28,
  19. width: size.width * 0.38,
  20. imageUrl: productModel.imageUrl![index],
  21. boxFit: BoxFit.fill,
  22. ),
  23. );
  24. }),
  25. )

请注意,我只翻译了代码部分,不包括代码中的注释。

英文:

I have fixed the problem by adding a sized box and giving it height and width. Thus, the problem was fixed thanks for your help everyone.

Here is my updated Pageview.builder code:

  1. child: SizedBox(
  2. height: 120,
  3. width: 400,
  4. child: productModel.imageUrl == null
  5. ? Image(
  6. height: size.width * 0.28,
  7. width: size.width * 0.38,
  8. fit: BoxFit.fill,
  9. image: AssetImage(&#39;lib/assets/images/error_image.png&#39;),
  10. )
  11. : PageView.builder(
  12. scrollDirection: Axis.horizontal,
  13. itemCount: productModel.imageUrl!.length,
  14. itemBuilder: (context, index) {
  15. return ClipRRect(
  16. borderRadius: BorderRadius.circular(10),
  17. child: FancyShimmerImage(
  18. height: size.width * 0.28,
  19. width: size.width * 0.38,
  20. imageUrl: productModel.imageUrl![index],
  21. boxFit: BoxFit.fill,
  22. ),
  23. );
  24. }),
  25. ),

huangapple
  • 本文由 发表于 2023年2月24日 10:07:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定