Flutter Flow: Carousel Menu
Flutter

Flutter Flow: Carousel Menu

November 19, 2023

I’m going to discuss how to make a simple carousel menu in the Flutter Flow platform. I will provide the full source code as well.

We are going to use the following package to help us achieve this: carousel_slider | Flutter Package

Note: Flutter Flow introduced data types. I walk through how to use data types instead of JSON in this new article Flutter Flow: Migrating the Carousel Menu to use data types

Custom Widget

First, let’s create our custom widget. Click the custom functions tab on the left-hand side of the flutter flow platform

Now click Add > Widget

Give your new widget a name such as CarouselMenu

We will need to pass JSON as a parameter to build our menu items. I will discuss this more later. Create a parameter called jsonMenuItems of type JSON.

Click the green View Boilerplate Code button.

It should show this screen.

Click Copy to Editor

Now click Save at the top right of the screen

Adding Carousel Slider dependency

Under the parameters add the carousel_slider dependency.

Click Save again. Then click Compile.

Adding JSON menu items to local state

For this example, we are going to store our menu items in Flutter Flow local state. You could also retrieve the JSON from an API.

Click on the Local State tab.

Now click Add State Variable.

Add a JSON field. You can name it the same as the parameter we created earlier.

Menu Item Example JSON

You can use this example JSON array to populate your menu carousel. This is a JSON Array containing three JSON Objects. Each object is a menu item and contains a title, route, and imageUrl. {% gist https://gist.github.com/cmcoffeedev/48cf66c91b930840df767d1abbd6968e.js %} If you look at the Flutter Flow source code you will see they use named routes to navigate in the app using the go router dependency. The route will be each screen’s Scaffold name. You will see this later.

Copy this JSON as the default value for the state variable we just created.

Save this using Ctrl-S/CMD-S.

Writing the custom carousel menu code

Go back to our custom widget so that we may implement the carousel menu.

First, add the import for the carousel_slider and go_router dependencies.

import 'package:go_router/go_router.dart';
import 'package:carousel_slider/carousel_slider.dart';

Create a class called CarouselItem and put it under _CarouselMenuState. This class will hold each menu item from the JSON.

Create a list variable of CarouselItem’s.

Under the carousel item list, let’s override initState. This method get’s called once when the widget first gets created. initState method - State class - widgets library - Dart API

Under initState, create a method to build our carousel widgets. This method doing 3 things.

  1. Iterating through each JSON Object in the JSON array.

  2. Creating a CarouselItem object with the current object’s value.

  3. Adding this object to the carouselItems list.

Let’s change our build method to return the carousel_slider.

Notice that I have context.pushNamed(route); commented out. This is the code FlutterFlow uses, but in the online editor, it will give you errors when compiling but will work when downloading the project.

There are some workarounds to get it to run on the Flutter Flow platform. Essentially, after you launch the app in test mode, uncomment the code, save it, and click instant reload.

Alternatively, we can instead use the following:

GoRouter.of(context).go(route);

Save and compile what we have so far.

Setting up screens to run our custom widget

Next, go to the Widget Tree tab to create our screens.

Create four screens. One that has our custom widget and three others that the carousel items will navigate to. These are the names that you will use as the route in the custom JSON state.

On the page/screen you want your custom widget, go to the UI Builder and drag and drop the custom widget.

Here are my settings for the custom widget.

Notice I set the JSON variable from our local state JSON variable.

Save the project and click the run in test mode button on the top right.

To test clicking the menu items, go back to the custom code and uncomment it. Save and then compile it. Go back to Test Mode and click instant reload. This will work fine when you download the code.

Here is the full source code:

// Automatic FlutterFlow imports
import '../../backend/backend.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_util.dart';
import '../widgets/index.dart'; // Imports other custom widgets
import '../../flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom widget code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:carousel_slider/carousel_slider.dart';
import 'package:go_router/go_router.dart';

class CarouselMenu extends StatefulWidget {
  const CarouselMenu({
    Key? key,
    this.width,
    this.height,
    this.jsonMenuItems,
  }) : super(key: key);

  final double? width;
  final double? height;
  final dynamic jsonMenuItems;

  @override
  _CarouselMenuState createState() => _CarouselMenuState();
}

class _CarouselMenuState extends State<CarouselMenu> {
  List<CarouselItem> carouselItems = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    buildCarouselWidgets();
  }

  void buildCarouselWidgets() {
    for (var data in widget.jsonMenuItems) {
      carouselItems
          .add(CarouselItem(data['imageUrl'], data['title'], data['route']));
    }
  }

  @override
  Widget build(BuildContext context) {
    return CarouselSlider.builder(
      itemCount: carouselItems.length,
      itemBuilder: (context, index, realIndex) {
        var item = carouselItems[index];
        var title = item.title;
        var route = item.route;
        var imageUrl = item.imageUrl;
        return GestureDetector(
          onTap: () {
            GoRouter.of(context).go(route);
          },
          child: Column(
            children: [
              Expanded(
                  child:
                      Image.network(imageUrl, fit: BoxFit.cover, width: 1000)),
              Text(title)
            ],
          ),
        );
      },
      options: CarouselOptions(
        autoPlay: false,
        enlargeCenterPage: true,
        aspectRatio: 2.0,
      ),
    );
  }
}

class CarouselItem {
  String imageUrl = "";
  String title = "";
  String route = "";
  CarouselItem(String imageUrl, String title, String route) {
    this.imageUrl = imageUrl;
    this.title = title;
    this.route = route;
  }
}


You can generate any widget including maps with custom markers, polylines, polygons, etc at https://codewhims.com/

Check out my other Flutter Flow articles FlutterFlow Stepper Form with Firebase Firestore Flutter Flow: Get Value From Multiple-Choice Choice Chips Flutter Flow: Carousel Menu Flutter Flow: Migrating the Carousel Menu to use data types Flutter Flow: Adding Custom Markers for Google Maps Flutter Flow: Use Supabase to show custom markers on Google Maps

Ready to Build Something Amazing?

Whether you need development expertise or technical consultation, I'm here to help bring your ideas to life.