在Flutter中创建尖角/斜角小部件

时间:2019-05-04 21:45:21

标签: dart flutter

如何在Flutter中创建这种倾斜形状?它应该支撑一个孩子,该孩子可以在居中大小变化时居中并缩放。

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以将ClipPathBeveledRectangleBorder一起使用

示例

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Custom Shape',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CustomShapeDemo(),
    );
  }
}

class CustomShapeDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Custom Shape Demo'),
        ),
        body: Center(
          child: ClipPath(
            clipper: ShapeBorderClipper(
              shape: BeveledRectangleBorder(
                  borderRadius: BorderRadius.circular(100.0)),
            ),
            child: Container(
              height: 200.0,
              width: 400.0,
              color: Colors.red,
              child: Center(
                child: Text('80',
                    style: TextStyle(color: Colors.white, fontSize: 85.0)),
              ),
            ),
          ),
        ));
  }
}

结果

enter image description here

答案 1 :(得分:1)

自定义剪切路径

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ClipPath(
          clipper: Sky(),
          child: Container(
            width: 400,
            height: 200,
            color: Colors.red,
            child: Center(
              child: Text('80',
                  style: TextStyle(color: Colors.white, fontSize: 85.0)),
            ),
          ),
        ),
      ),
    );
  }
}

class Sky extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    double h = size.height;
    double w = size.width;

    double xOffset = 0.1;
    Path path = Path()
      ..lineTo(w * xOffset, h)
      ..lineTo(w - w * xOffset, h)
      ..lineTo(w, h / 2)
      ..lineTo(w - w * xOffset, 0)
      ..lineTo(w * xOffset, 0.0)
      ..lineTo(0.0, h / 2)
      ..lineTo(w * xOffset, h);
    return path;
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return true;
  }
}

enter image description here