добавить метод ontap () в мой список в флаттере - PullRequest
0 голосов
/ 17 июня 2019

для добавления метода ontap () в мой список с пользовательским классом, который я сделал для этого вида плитки

я пытался добавить ontap (): но не узнал, что это говорит вот код

class _MenuCard extends StatelessWidget {

  final String headImageAssetPath;
  final IconData icon;
  final Color iconBackgroundColor;
  final String title;
  final String subtitle;
  final int heartCount;

  _MenuCard({
    this.headImageAssetPath,
    this.icon,
    this.iconBackgroundColor,
    this.title,
    this.subtitle,
    this.heartCount,
  });

  @override
  Widget build(BuildContext context) {
    return new Padding(
      padding: const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
      child: new Card(
        elevation: 10.0,
        child: new Column(
          children: [
            new Image.asset(
              headImageAssetPath,
              width: double.infinity,
              height: 100.0,
              fit: BoxFit.cover,
            ),
            new Row(
              children: [
                new Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: new Container(
                    padding: const EdgeInsets.all(10.0),
                    decoration: new BoxDecoration(
                      color: iconBackgroundColor,
                      borderRadius: new BorderRadius.all(const Radius.circular(15.0)),
                    ),
                    child: new Icon(
                      icon,
                      color: Colors.white,
                    ),
                  ),
                ),
                new Expanded(
                  child: new Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      new Text(
                        title,
                        style: const TextStyle(
                          fontSize: 25.0,
                          fontFamily: 'mermaid',
                        ),
                      ),
                      new Text(
                        subtitle,
                        style: const TextStyle(
                          fontSize: 16.0,
                          fontFamily: 'bebas-neue',
                          letterSpacing: 1.0,
                          color: const Color(0xFFAAAAAA),
                        ),
                      ),
                    ],
                  ),
                ),
                new Container(
                  width: 2.0,
                  height: 70.0,
                  decoration: new BoxDecoration(
                    gradient: new LinearGradient(
                      colors: [
                        Colors.white,
                        Colors.white,
                        const Color(0xFFAAAAAA),
                      ],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    ),
                  ),
                ),
                new Padding(
                  padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                  child: new Column(
                    children: [
                      new Icon(
                        Icons.favorite_border,
                        color: Colors.red,
                      ),
                      new Text(
                        '$heartCount',
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

этот код относится к классу, который я использую для создания своего списка в скаффолде виджета без состояния. и вот как я строю свой listview после возвращения леса в тело: код ниже

body: new ListView(
          children: [
            new _MenuCard(
                headImageAssetPath: 'images/img.png',
                icon: Icons.fastfood,
                iconBackgroundColor: Colors.orange,
                title: 'il domacca',
                subtitle: "78 5TH AVENUE, NEW YORK",
                heartCount: 84
            ),
            new _MenuCard(
                headImageAssetPath: 'images/img.png',
                icon: Icons.local_dining,
                iconBackgroundColor: Colors.red,
                title: 'Mc Grady',
                subtitle: "79 5TH AVENUE, NEW YORK",
                heartCount: 84
            ),
            new _MenuCard(
                headImageAssetPath: 'images/img.png',
                icon: Icons.fastfood,
                iconBackgroundColor: Colors.purpleAccent,
                title: 'Sugar & Spice',
                subtitle: "80 5TH AVENUE, NEW YORK",
                heartCount: 84
            ),
          ]
      ),

1 Ответ

0 голосов
/ 17 июня 2019

Вы можете обернуть свой пользовательский виджет элемента списка внутри GestureDetector, который имеет метод обратного вызова onTap, который вы можете указать.

Пример -

class _MenuCard extends StatelessWidget {

  final String headImageAssetPath;
  final IconData icon;
  final Color iconBackgroundColor;
  final String title;
  final String subtitle;
  final int heartCount;
  final VoidCallback onTapCallback; //Add this custom onTap method

  _MenuCard({
    this.headImageAssetPath,
    this.icon,
    this.iconBackgroundColor,
    this.title,
    this.subtitle,
    this.heartCount,
    this.onTapCallback,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTapCallback,
      child: new Padding(
        padding: const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
        child: //Rest of your code
      ),
    );
  }

}

И внутри ListViewВы можете указать свой пользовательский onTapCallback.

body: new ListView(
  children: [
    new _MenuCard(
      headImageAssetPath: 'images/img.png',
      icon: Icons.fastfood,
      iconBackgroundColor: Colors.orange,
      title: 'il domacca',
      subtitle: "78 5TH AVENUE, NEW YORK",
      heartCount: 84,
      onTapCallback: () {
        // Your onTap code goes here
      }
    ),
    // Rest of your code
  ]
)

Помимо onTap, виджет GestureDetector также имеет множество других обратных вызовов пользовательских событий.Вы можете узнать больше о них здесь .

Кроме того, та же функциональность также может быть достигнута с помощью виджета InkWell, вам просто нужно заменить GestureDetector наInkWell и остальная часть кода останется прежней.Документацию для виджета можно найти здесь .

Надеюсь, это поможет!

...