skip to Main Content

I am creating a home screen for my application where on top there is username with their photo below there is a slider after that there is a categories tiles and below that all the recipes will be shown in 2 columns(grid view). I am getting a error may it is related to viewport I don’t know where I am making a mistake and what actually causing the mistake. I also try to find solution on different websites such as chatGPT but didn’t get the proper solution for the problem

Every effort will be appreciated. thank you 🙂

Code:

import 'dart:async';
import 'package:flutter/material.dart';
import '../Admin/recipes/category_tile.dart';
import '../Admin/recipes/recipe_card.dart';
import '../Admin/recipes/recipe_card_slider.dart';
import '../Database/databaseHelper.dart';
import '../WidgetsAndUtils/automated_slider.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List<Map<String, dynamic>> categories = [
    {
      'image': 'assets/appetizer.jpg',
      'title': 'Appetizer',
    },
    {
      'image': 'assets/breakfast.jpg',
      'title': 'Breakfast',
    },
    {
      'image': 'assets/dinner.jpeg',
      'title': 'Dinner',
    },
    {
      'image': 'assets/dinner.jpeg',
      'title': 'Dinner',
    },
    // more maps can be added here
  ];

  late List<Map<String, dynamic>> recipesSlider;
  late List<Map<String, dynamic>> recipes;
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    loadData();
  }

  Future<void> loadData() async {
    recipesSlider = await getRecipesDataFromLocalDatabaseSlider();
    recipes = await getRecipesDataFromLocalDatabase();
    await Future.delayed(const Duration(seconds: 3));
    setState(() {
      isLoading = false;
    });
  }

  Future<List<Map<String, dynamic>>>
      getRecipesDataFromLocalDatabaseSlider() async {
    List<Map<String, dynamic>> recipes =
        await DatabaseHelper().random5Recipes();
    await Future.delayed(const Duration(seconds: 3));
    return recipes;
  }

  Future<List<Map<String, dynamic>>> getRecipesDataFromLocalDatabase() async {
    List<Map<String, dynamic>> recipes = await DatabaseHelper()
        .getAllRecipe('recipes', 'All', 'All', 'All', 'All');
    await Future.delayed(const Duration(seconds: 3));
    return recipes;
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: const Color(0XFFECECEC),
      //backgroundColor: Color(0XFF212121),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            //User's name and picture
            Container(
              padding: const EdgeInsets.only(
                left: 25.0,
                right: 25.0,
                top: 40,
                bottom: 25.0,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: const [
                      Text(
                        'Hi, Arnold',
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 28,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        'Ready to cook for dinner?',
                        style: TextStyle(
                          color: Colors.black54,
                          fontSize: 17,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                  Container(
                    width: 55.0,
                    height: 55.0,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20.0),
                      color: Colors.grey[300],
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(20.0),
                      child: Image.network(
                        'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSmbCUztgZQXeFQY-BvGs__KnpO6vWCYUwTf7MXM-PPt1xnsuW1k7L5Pv7CabRSGETu_Y&usqp=CAU',
                        fit: BoxFit.cover,
                      ),
                    ),
                  )
                ],
              ),
            ),
            //Recipes Slider
            isLoading
                ? CircularProgressIndicator()
                : AutomatedSlider(
                    items: List.generate(
                      5,
                      (index) => RecipeCardSlider(
                        isAdmin: false,
                        ID: (recipesSlider[index]['recipeId']).toString(),
                        title: recipesSlider[index]['recipeName'],
                        description: recipesSlider[index]['recipeDescription'],
                        course: recipesSlider[index]['recipeCourse'],
                        diet: recipesSlider[index]['recipeDiet'],
                        cookTime: recipesSlider[index]['recipeTime'],
                        rating:
                            (recipesSlider[index]['recipeRating']).toString(),
                        thumbnailUrl: recipesSlider[index]['recipeURL'],
                        ingredients: recipesSlider[index]['recipeIngredients']
                            .split(',')
                            .map((e) => e.trim())
                            .toList(),
                      ),
                    ),
                    itemCount: 5,
                  ),
            SizedBox(
              height: size.height * 0.03,
            ),
            //Categories Heading
            Container(
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.only(
                left: 25.0,
                right: 25.0,
              ),
              child: const Text(
                'Categories',
                style: TextStyle(
                  fontSize: 24.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            SizedBox(
              height: size.height * 0.015,
            ),
            //Horizontal Category Tiles
            SizedBox(
              height: 70,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                padding: const EdgeInsets.only(top: 0),
                itemCount: categories.length,
                itemBuilder: (context, index) {
                  return CategoryTile(
                    image: categories[index]['image'],
                    text: categories[index]['title'],
                  );
                },
              ),
            ),
            SizedBox(
              height: size.height * 0.03,
            ),
            //Recipes Grid
            isLoading
                ? CircularProgressIndicator()
                : Container(
                    padding: const EdgeInsets.all(16.0),
                    child: GridView.builder(
                      itemCount: recipes.length,
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        crossAxisSpacing: 16.0,
                        mainAxisSpacing: 16.0,
                      ),
                      itemBuilder: (BuildContext context, int index) {
                        return ListView.builder(
                          padding: const EdgeInsets.only(top: 0),
                          itemCount: recipes.length,
                          itemBuilder: (context, index) {
                            return RecipeCardSlider(
                                isAdmin: false,
                                ID: (recipes[index]['recipeId']).toString(),
                                title: recipes[index]['recipeName'],
                                description: recipes[index]
                                    ['recipeDescription'],
                                course: recipes[index]['recipeCourse'],
                                diet: recipes[index]['recipeDiet'],
                                cookTime: recipes[index]['recipeTime'],
                                rating:
                                    (recipes[index]['recipeRating']).toString(),
                                thumbnailUrl: recipes[index]['recipeURL'],
                                ingredients: recipes[index]['recipeIngredients']
                                    .split(',')
                                    .map((e) => e.trim())
                                    .toList());
                          },
                        );
                      },
                    ),
                  ),
          ],
        ),
      ),
    );
  }
}

Error:

======== Exception caught by rendering library ===================================================== The following assertion was thrown during performResize(): Vertical viewport was
given unbounded height.

Viewports expand in the scrolling direction to fill their container.
In this case, a vertical viewport was given an unlimited amount of
vertical 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 vertical
space for the children. In this case, consider using a Column or Wrap
instead. Otherwise, consider using a CustomScrollView to concatenate
arbitrary slivers into a single scrollable.

The relevant error-causing widget was: GridView
GridView:file:///E:/FYP/Code/Recipedia/lib/Tabs/home_screen_new.dart:202:37
When the exception was thrown, this was the stack:
#0 RenderViewport.computeDryLayout. (package:flutter/src/rendering/viewport.dart:1427:15)
#1 RenderViewport.computeDryLayout (package:flutter/src/rendering/viewport.dart:1488:6)
#2 RenderBox.performResize (package:flutter/src/rendering/box.dart:2441:12)
#3 RenderObject.layout (package:flutter/src/rendering/object.dart:2168:9)
#4 RenderBox.layout (package:flutter/src/rendering/box.dart:2430:11)
#5 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:120:14)
#6 RenderObject.layout (package:flutter/src/rendering/object.dart:2189:7)
#7 RenderBox.layout (package:flutter/src/rendering/box.dart:2430:11)

2

Answers


  1. The Problem is that the Columns are not limited in height. They will expand as much as they can and since they are wrapped into a scrollview, that would be infinite. Try to add this to your columns:

    mainAxisSize: MainAxisSize.min
    
    Login or Signup to reply.
  2. this error occur when ever you try to create ListView or PageView in other widget that dose not contains height and width!.
    for ListView you should specify the height or make shirnkWrap true
    for PageView you should specify the width of that widget
    in your code you have to specify them

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search