Flutter: How do you make a card clickable?

后端 未结 6 1328
迷失自我
迷失自我 2020-12-15 02:40

I just have a simple Card like new Card(child: new Text(\'My cool card\')) and I want to be able to click anywhere on it to run some function, except there\'s n

相关标签:
6条回答
  • 2020-12-15 02:50

    Flutter provides the InkWell Widget. by registering a callback you can decide what happens when user clicks on the card (called tap in flutter). InkWell also implements Material Design ripple effect

    Card(
      child: new InkWell(
        onTap: () {
          print("tapped");
        },
        child: Container(
          width: 100.0,
          height: 100.0,
        ),
      ),
    ),
    
    0 讨论(0)
  • 2020-12-15 02:52

    Flutter use composition over properties. Wrap the desired widget into a clickable one to achieve what you need.

    Some clickable widgets : GestureDetector, InkWell, InkResponse.

    GestureDetector(
      onTap: () => ......,
      child: Card(...),
    );
    
    0 讨论(0)
  • 2020-12-15 02:57

    In Flutter, InkWell is a material widget that responds to touch action.

    InkWell(
        child: Card(......),
        onTap: () { 
            print("Click event on Container"); 
        },
    );
    

    GestureDetector is a widget that detects the gestures.

    GestureDetector(
        onTap: () { 
            print("Click event on Container"); 
        },
        child: Card(.......),
    )
    

    Difference

    InkWell is a material widget and it can show you a Ripple Effect whenever a touch was received.

    GestureDetector is more general-purpose, not only for touch but also for other gestures.

    0 讨论(0)
  • 2020-12-15 03:05

    I think you can also use InkWell apart from GestureDetector just wrap the card inside InkWell() Widget

    InkWell(
      onTap: (){ print("Card Clicked"); }
      child: new Card(),
    );
    
    0 讨论(0)
  • 2020-12-15 03:05

    The most preferred way is to add ListTile as Card child. Not only does ListTile contain the method onTap it also helps you in making Card interesting.

    Card(
      child: ListTile(
        title: Text('Title')
        leading: CircleAvatar(
          backgroundImage: AssetImage('assets/images/test.jpg'),
        ),
        onTap: () {
          print('Card Clicked');
        },
      ),
    ),
    
    0 讨论(0)
  • 2020-12-15 03:08

    You can use Inkwell and insert splashColor which, at the click of the user, creates the rebound effect with the chosen color, on the card .. This is mainly used in material design.

    return Card(
      color: item.completed ? Colors.white70 : Colors.white,
      elevation: 8,
      child: InkWell(
          splashColor: "Insert color when user tap on card",
          onTap: () async {
    
          },
        ),
    );
    
    0 讨论(0)
提交回复
热议问题