Relation Flutter: CooKingKong App – Step 4

What is relation? When we use the word, we mean connection between two or many persons. Now, it is true for relation in Flutter also.

Why?

Because, in Flutter we use many objects. Right? For that reason, these objects may have relations.

Now, relation may be different.

Firstly, It can be one to one object. Secondly, it can be one to many objects. And, finally, it can be many to many objects.

In our App, we have only categories. And we have seen that there are many categories that we can display through GridView.

As a result we see all categories on the home page.

Flutter navigation send data_ categories page
Flutter navigation send data_ categories page

When we click any category, we see that category page. If we click Mexican, we will see the Mexican category.

Flutter navigation send data to a page
Flutter navigation sends data to a page

As we can see, the category comes with the title and color. But there should be Food items which belong to that category. Isn’t it?

Because, Mexican category may have different food items. Right?

Therefore each category should display those food items on the corresponding page.

Here comes the challenge to establish the relation in Flutter. Each category has many food items. In other words, each food may have many categories.

As a result, they have a relation. So our next challenge is to establish this relation in Flutter. So that finally we can click any food item to see its funny recipe.

Why we need relation in Flutter

As we have said earlier, our category page should display various food items on the page. To make that happen, we must have a food class and dummy food items.

In addition, those food items may have different properties. We will see that in a minute.

Firstly, we try to understand one key concept in relation flutter.

What is that?

In Food class, we can have a list of categories as its property. And, in that list we can place different categories.

Therefore the vary first food may have three categories. That means the first food may belong to African, Mexican and Indian category.

There is a connection, and there is also a commonness. That is why we need to establish the relation in Flutter.

Secondly, we will look at the food class.

enum Complexity {
  simple,
  complex,
}

class LorenIpsumFood {
  final String id;
  final List<String> categoryID;
  final String title;
  final String imageUrl;
  final List<String> ingredients;
  final List<String> steps;
  final int duration;
  final Complexity complexity;
  final bool isVegan;
  final bool isVegetarian;

  const LorenIpsumFood({
    required this.id,
    required this.categoryID,
    required this.title,
    required this.imageUrl,
    required this.ingredients,
    required this.steps,
    required this.duration,
    required this.complexity,
    required this.isVegan,
    required this.isVegetarian,
  });
}

In the above code, we have many instance variables. Two of them of the enum type. We have discussed enum earlier. If you are a beginner, please read that section.

However, we have established relation in Flutter with one property in Food class.

final List<String> categoryID;

Now we will create a few items of food. To do that, we create many instances by passing values through class constructor.

import 'food.dart';

const dummyLorenIpsumLorenIpsumFood = [
  LorenIpsumFood(
    id: 'f1',
    categoryID: ['c1', 'c2', 'c8'],
    title: 'Lorem ipsum dolor sit amet',
    complexity: Complexity.simple,
    imageUrl:
        'https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg/800px-Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg',
    duration: 20,
    ingredients: [
      '1 Lorem ipsum dolor sit amet, consectetur adipiscing elit',
      '1 Lorem ipsum dolor sit amet',
      '1 Lorem ipsum dol',
      '250g Lorem ipsum dolor',
      'Lorem ipsum',
      'Lorem ipsum dolor'
    ],
    steps: [
      'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      'Lorem ipsum dolor sit amet, consectetur.',
      'Lorem ipsum dolo, consectetur adipiscing elit.',
      'Lorem ipsum dolor sit amet, consectetur.',
      'Lorem ipsum dolor sit amet, adipiscing elit.',
      'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      'Lorem ipsum dolor sit amet.'
    ],
    isVegan: true,
    isVegetarian: true,
  ),
  LorenIpsumFood(
    id: 'f2',
    categoryID: ['c2', 'c5', 'c4'],
    title: 'Lorem ipsum',
    complexity: Complexity.simple,
...
// code is incomplete for brevity

As we see, the first food object has three category properties. In the similar vein, the second food item also belongs to three categories.

Now, all food titles can come on the individual category page.

So we need to change the code of the “IndividualCategoryPage” Widget.

How to establish relation in Flutter

Here lies our main challenge. The dummy food list contains a list of category id. Therefore, we can map that list and return each category id.

The Dart List type has a “where” method that can map through the items and return the list of items.

As a result, we can take an advantage of that List method.

Therefore, we should change the code of the “IndividualCategoryPage” Widget.

import 'package:flutter/material.dart';

import '../model/dummy_foods.dart';

class IndividualCategoryPage extends StatelessWidget {
  const IndividualCategoryPage({
    Key? key,
  }) : super(key: key);

  static const routeName = '/individual-category-page';

  @override
  Widget build(BuildContext context) {
    final routeArguments =
        ModalRoute.of(context)!.settings.arguments as Map<String, Object>;
    final id = routeArguments['id'];
    final Object? title = routeArguments['title'];
    final Color? color = routeArguments['color'] as Color;
    final categoryMeals = dummyLorenIpsumLorenIpsumFood.where((food) {
      return food.categoryID.contains(id);
    }).toList();

    return Scaffold(
      appBar: AppBar(
        title: Text(title.toString()),
      ),
      body: ListView.builder(
        itemBuilder: (ctx, index) {
          return Container(
            padding: const EdgeInsets.all(18.0),
            color: color,
            child: Text(
              categoryMeals[index].title,
              style: Theme.of(context).textTheme.bodyMedium,
            ),
          );
        },
        itemCount: categoryMeals.length,
      ),
    );
  }
}

Now we can tap any category and get all the titles of the food items.

These food items belong to that category.

First, we tap the Mexican category to see what food items are there.

Relation in Flutter first example
Relation in Flutter first example

Four food titles are there.

Next, we tap the French category. It has two food items. Because when we have created Food objects, we pass this category id in two cases.

As a result, the category French has two food titles.

Relation in Flutter second example
Relation in Flutter second example

However, our CooKingKong App is not finished yet. We have just scratched the surface.

Now we understand that we can display the food items with title and image.

At the same time, we can also use Flutter named route to navigate to the individual Food page where we can show our funny recipe.

To do that, we need to change the design and the business logic.

In the next section we will discuss that.

So stay tuned.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

One response to “Relation Flutter: CooKingKong App – Step 4”

  1. […] the relation between the pages becomes complex, we need to be careful. Why? Because we have been handling List and Map. When we iterate Flutter […]

Leave a Reply