简体   繁体   中英

How to make a custom button shape in flutter

I am working on a project and i want to achieve a button像这样

How can i easily make this shape.

You can use a CustomPainter . Have a look at this great example on how to use this.

Here is a small example of what you want to achieve (though I didn't do the rounded border but you can easily expand:

import 'package:flutter/material.dart';

main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Drawing Paths',
      home: Scaffold(
        body: Center(
          child: GestureDetector(
            onTap: () => print('Do Something'),
            child: CustomPaint(
              size: Size(200, 50),
              painter: CurvePainter(),
            ),
          ),
        ),
      ),
    );
  }
}

class CurvePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
      ..color = Color(0xFFE32087)
      ..style = PaintingStyle.fill;

    var path = Path()
      ..moveTo(size.width*0.2, 0)
      ..lineTo(size.width, size.height*0.2)
      ..lineTo(size.width, size.height)
      ..lineTo(0, size.height);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

The result :

按钮图片

Either use an image which represents this button and wrap it with GestureDetector (not recommended but sometimes the UI is so complex that making it purely in Flutter might be overkill, so keeping this option in mind is not bad) or play around with CustomClipper !

What you want to do is creating a Container or FlatButton and wrap it with ClipPath where you provide a CustomClipper as the clipper property of ClipPath . In your implementation of CustomClipper you shape the widget just ike you want it to. Check out this great Medium post (not written by me, credits go to Kinjal Dhamat) where she explains various ways how to use CustomClipper and shape everything you want:

https://medium.com/flutter-community/flutter-custom-clipper-28c6d380fdd6

As suggested by pskink, creating a custom ShapeBorder class, which will be set as the shape property of FlatButton for example, has quite some benefits but need some additional knowledge, take a look at this post:

Flutter - ClipPath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM