0

I am a newbie to Flutter and Dart, and am trying to create a clickable container class that is based on the GestureDetector class. My code for my container is shown below:

class CustomWidget extends GestureDetector
{
   final aTitle;

   CustomWidget(this.aTitle)
   {
     onTap() {
       print("$aTitle was pressed!");
     }

     child: new Container(
       padding: const EdgeInsets.all(8),
       child: Text(aTitle),
       color: Colors.blueGrey[200],
     );
   }
}

I am attempting to display this widget in my main application screen using the following code in the body of my app widget:

  body: CustomScrollView(
    primary: false,
    slivers: <Widget>[
      SliverPadding(
        padding: const EdgeInsets.all(20),
        sliver: SliverGrid.count(
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
          crossAxisCount: 2,
          children: <Widget>[
            CustomWidget('Test Display'),
          ],
        ),
      ),
    ],
  ),

I seem to have two problems: (1) my development environment is telling me that my onTap() method is "unused", indicating that it will not capture tap events, and (2) that doesn't seem to matter much because the CustomWidget instance that I am creating in the app widget is not appearing on my screen.

I am clearly missing something. Can someone help me correct my code so that my custom widget will be displayed and process onTap events?

1 Answer 1

1

Generally speaking, the CustomWidget is a good idea, but inheritance is the wrong implementation. Flutter strongly favors composition over inheritance.

Your custom widget using composition:

class CustomWidget extends StatelessWidget {
  final String title;
  
  const CustomWidget(this.title);
  
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
       print("$title was pressed!");
      },
     child: new Container(
       padding: const EdgeInsets.all(8),
       child: Text(title),
       color: Colors.blueGrey[200],
     ));
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.