自定义Flutter中的小部件的点击效果

时间:2019-01-05 08:25:44

标签: flutter flutter-layout

如何在Flutter中自定义窗口小部件的点击效果,可以在Android中对其进行配置:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
           android:drawable="@drawable/btn_pressed"
/>
<!-- pressed -->
<item android:state_focused="true"
           android:drawable="@drawable/btn_normal"
/>
<!-- focused -->
<item android:drawable="@drawable/btn_normal"
/>
<!-- default -->
</selector>

我想问一下如何在Flutter中实现它。谢谢!

1 个答案:

答案 0 :(得分:0)

使用此功能,您可以自定义点击效果

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: 'My App',
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  bool isTapped = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My App'),
      ),
      body: Center(
        child: GestureDetector(
          onTapDown: (value) {
            setState(() {
              print('onTapDown');
              isTapped = true;
            });
          },
          onTapUp: (value) {
            setState(() {
              print('onTapUp');
              isTapped = false;
            });
          },
          onTapCancel: () {
            setState(() {
              print('onTapCancel');
              isTapped = false;
            });
          },
          child: _getImage(),
        ),
      ),
    );
  }

  Widget _getImage() {
    AssetImage image = AssetImage('images/icon.png');
    return Image(
      image: image,
      width: 100.0,
      height: 100.0,
      color: isTapped ? Colors.deepOrangeAccent : Colors.orange,
    );
  }
}