skip to Main Content

New to flutter and trying to learn about InkWell, but doesn’t seem to be working properly as I can’t get it to do anything. I have also tried to use the box I’m clicking on to taking me to another page with no luck. Below is snippets of the code. Any help is greatly appreciated. This is also following a training course and I have gone back and reviewed it and googled as much as I could to determine this issue with no luck.

main.dart

import 'package:flutter/material.dart';

import 'package:google_fonts/google_fonts.dart';
import 'package:wtpa/screens/categories.dart';

final theme = ThemeData(
  useMaterial3: true,
  colorScheme: ColorScheme.fromSeed(
    brightness: Brightness.dark,
    seedColor: const Color.fromARGB(255, 131, 57, 0),
  ),
  textTheme: GoogleFonts.latoTextTheme(),
);

void main() {
  runApp(const App());
}

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: theme,
      home: const CategoriesScreen(),
    );
  }
}

categories.dart

import 'package:flutter/material.dart';

import 'package:wtpa/Data/dummy_data.dart';
import 'package:wtpa/screens/meals.dart';
import 'package:wtpa/widgets/category_grid_item.dart';
import 'package:wtpa/models/category.dart';

class CategoriesScreen extends StatelessWidget {
  const CategoriesScreen({super.key});

  void _selectCategory(BuildContext context, Category category) {
    final filteredMeals = dummyMeals
        .where((meal) => meal.categories.contains(category.id))
        .toList();

    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (ctx) => MealsScreen(
          title: category.title,
          meals: filteredMeals,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Pick your category'),
      ),
      body: GridView(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 3 / 2,
          crossAxisSpacing: 20,
          mainAxisSpacing: 20,
        ),
        children: [
          for (final category in availableCategories)
            CategoryGridItem(
              category: category,
              onSelectCategory: () {
                _selectCategory(context, category);
              },
            )
        ],
      ),
    );
  }
}

category.dart

import 'package:flutter/material.dart';

class Category {
  const Category({
    required this.id,
    required this.title,
    this.color = Colors.orange,
  });

  final String id;
  final String title;
  final Color color;
}

category_grid_item.dart

import 'package:flutter/material.dart';

import 'package:wtpa/models/category.dart';

class CategoryGridItem extends StatelessWidget {
  const CategoryGridItem({
    super.key,
    required this.category,
    required this.onSelectCategory,
  });

  final Category category;
  final void Function() onSelectCategory;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {},
      splashColor: Theme.of(context).primaryColor,
      borderRadius: BorderRadius.circular(48),
      child: Container(
        padding: const EdgeInsets.all(24),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(48),
          gradient: LinearGradient(
            colors: [
              category.color.withOpacity(0.55),
              category.color.withOpacity(0.9),
            ],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
        ),
        child: Text(
          category.title,
          style: Theme.of(context).textTheme.titleLarge!.copyWith(
                color: Theme.of(context).colorScheme.onSurface,
              ),
        ),
      ),
    );
  }
}

2

Answers


  1. As others have mentioned, if you want a tap action to be handled by your InkWell, you need to set it to do something.

    In your code you have:

    @override
      Widget build(BuildContext context) {
        return InkWell(
          onTap: () {},             ///// <---- HERE
          splashColor: Theme.of(context).primaryColor,
          borderRadius: BorderRadius.circular(48),
          child: Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(48),
              gradient: LinearGradient(
                colors: [
                  category.color.withOpacity(0.55),
                  category.color.withOpacity(0.9),
                ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
            ),
            child: Text(
              category.title,
              style: Theme.of(context).textTheme.titleLarge!.copyWith(
                    color: Theme.of(context).colorScheme.onSurface,
                  ),
            ),
          ),
        );
      }
    }
    

    so you have an empty callback for the onTap method. In order for your tap action to do something when the InkWell is tapped, you need to implement this.
    I.E., navigate to somewhere:

    @override
      Widget build(BuildContext context) {
        return InkWell(
          onTap: () {
              Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const YourOtherScreen())
           },
          splashColor: Theme.of(context).primaryColor,
          borderRadius: BorderRadius.circular(48),
          child: Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(48),
              gradient: LinearGradient(
                colors: [
                  category.color.withOpacity(0.55),
                  category.color.withOpacity(0.9),
                ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
            ),
            child: Text(
              category.title,
              style: Theme.of(context).textTheme.titleLarge!.copyWith(
                    color: Theme.of(context).colorScheme.onSurface,
                  ),
            ),
          ),
        );
      }
    }
    

    You can see another example in the documentation.

    Login or Signup to reply.
  2. I could not reproduce this issue. In case it helps, here is an adaptation of the counter sample app. Instead of incrementing a counter it adds CategoryGridItems to a grid.

    You could paste it into a dartpad and try it out.

    // Copyright 2019 the Dart project authors. All rights reserved.
    // Use of this source code is governed by a BSD-style license
    // that can be found in the LICENSE file.
    
    import 'package:flutter/material.dart';
    
    class Category {
      const Category({
        this.title = '',
        this.color = Colors.blue,
      });
      final Color color;
      final String title;
    }
    
    class CategoryGridItem extends StatelessWidget {
      const CategoryGridItem({
        super.key,
        required this.category,
        required this.onSelectCategory,
      });
    
      final Category category;
      final void Function() onSelectCategory;
    
      @override
      Widget build(BuildContext context) {
        return InkWell(
          onTap: onSelectCategory,
          splashColor: Theme.of(context).primaryColor,
          borderRadius: BorderRadius.circular(48),
          child: Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(48),
              gradient: LinearGradient(
                colors: [
                  category.color.withOpacity(0.55),
                  category.color.withOpacity(0.9),
                ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
            ),
            child: Text(
              category.title,
              style: Theme.of(context).textTheme.titleLarge!.copyWith(
                    color: Theme.of(context).colorScheme.onSurface,
                  ),
            ),
          ),
        );
      }
    }
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            colorSchemeSeed: Colors.blue,
          ),
          home: const MyHomePage(title: 'Inkwell Demo'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      final String title;
    
      const MyHomePage({
        super.key,
        required this.title,
      });
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
      Color color = Colors.blue;
      final List<CategoryGridItem> categoryGridItems = [];
    
      void _incrementCounter() {
        setState(() {
          _counter++;
          color = color.withGreen(color.green + 10);
          categoryGridItems.add(CategoryGridItem(
            category: Category(title: 'Category $_counter, $color',color:  color),
            onSelectCategory: () {},
          ));
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'You have pressed add $_counter times.',
                style: Theme.of(context).textTheme.headlineMedium,
              ),
              Container(
                  height: 500,
                  child: GridView(
                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      childAspectRatio: 3 / 2,
                      crossAxisSpacing: 20,
                      mainAxisSpacing: 20,
                    ),
                    children: [...categoryGridItems],
                  )),
            ],
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Add category',
            child: const Icon(Icons.add),
          ),
        );
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search