繁体   English   中英

制作可重用的颤动小部件

[英]Making reusable flutter widget

我是 flutter 的新手,我一直在尝试使我的自定义小部件可重复使用,但一直在死胡同...我希望能够使用更改图标的颜色、卡片中的文本、第一张卡片以及随附的卡片...此外,我应该能够更改图标、图标内的文本以及每个按钮的点击功能应该能够在点击时执行不同的操作

class _CustomCardState extends State<CustomCard> { @override Widget build(BuildContext context) { return Card( margin: EdgeInsets.fromLTRB(20, 10, 20, 1), color: Colors.red, child: InkWell( onTap: (){}, child: ListTile( leading: Card( color: Colors.white, margin: EdgeInsets.all(5), child: Padding( padding: EdgeInsets.all(8.0), child: Icon( KycIcons.add_a_photo, size: 20, color: Colors.red, ), ), ), title: Text('Uplaod your selfie', style: TextStyle(color: Colors.white, fontSize: 16)), ), ), ); } }

这是一个非常简单的示例,说明如何构建可重用的小部件:

import 'package:flutter/material.dart';

class ContainerMain extends StatelessWidget {
  String text;
  Color color; 

  ContainerMain(this.text, {this.color = Colors.white});

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Container(
      alignment: Alignment.center,
      height: size.height / 10,
      width: size.width,
      child: Text(
        text,
        style: TextStyle(fontSize: 20, color: color),
      ),
    );
  }
}

这是我对你班级的贡献。 顺便说一句,它应该是StatelessWidget而不是StatefulWidget因为不涉及状态变量。

import 'package:flutter/material.dart';

class CustomCard extends StatefulWidget {
  final Color iconColor;
  final double iconSize;
  final Color cardColor;
  final Color innerCardColor;
  final String title;
  final TextStyle style;
  final void Function()? onTap;

  const CustomCard({
    Key? key,
    this.iconColor = Colors.red,
    this.iconSize = 20.0,
    this.cardColor = Colors.red,
    this.innerCardColor = Colors.white,
    this.title = 'Upload your selfie',
    this.style = const TextStyle(color: Colors.white, fontSize: 16),
    this.onTap,
  }) : super(key: key);

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

class _CustomCardState extends State<CustomCard> {
  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.fromLTRB(20, 10, 20, 1),
      color: widget.cardColor,
      child: InkWell(
        child: ListTile(
          leading: Card(
            color: widget.innerCardColor,
            margin: const EdgeInsets.all(5),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Icon(
                KycIcons.add_a_photo,
                size: iconSize,
                color: widget.iconColor,
              ),
            ),
          ),
          title: Text(widget.title, style: widget.style),
          onTap: widget.onTap,
        ),
      ),
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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