如何在Flutter中建立自定义的系统控件?

时间:2019-10-03 09:33:54

标签: flutter dart flutter-layout

我想用分段控件创建过滤器控件,但是它具有自定义形状,如图片所示 enter image description here

我可以使用分段控件来实现这一点,还是需要构建自己的控件?

1 个答案:

答案 0 :(得分:2)

类似的东西

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Title')),
        body: Center(
          child: RadioChips(
            values: ['All', 'Tradition', 'Fiesta'],
            onSelected: (index) {
              print('selected: $index');
            },
          ),
        ),
      ),
    );
  }
}

class RadioChips extends StatefulWidget {
  final List<String> values;
  final int initialPosition;
  final Function(int index) onSelected;

  RadioChips({@required this.values, @required this.onSelected, this.initialPosition = 0});

  @override
  _RadioChipsState createState() => _RadioChipsState();
}

class _RadioChipsState extends State<RadioChips> {
  int current;

  @override
  void initState() {
    super.initState();
    current = widget.initialPosition;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(
        widget.values.length,
        (index) {
          return GestureDetector(
            onTap: () async {
              setState(() => current = index);
              widget.onSelected(index);
            },
            child: Container(
              height: 36,
              alignment: Alignment.center,
              margin: const EdgeInsets.symmetric(horizontal: 4),
              padding: const EdgeInsets.symmetric(horizontal: 20),
              decoration: BoxDecoration(
                borderRadius: const BorderRadius.all(Radius.circular(18)),
                color: index == current ? Colors.lightBlue : Colors.grey[400],
              ),
              child: Text(widget.values[index], style: TextStyle(color: Colors.white)),
            ),
          );
        },
      ),
    );
  }
}

enter image description here