美文网首页
Flutter自定义View

Flutter自定义View

作者: woniu | 来源:发表于2022-08-01 17:30 被阅读0次

    自定义View的原则是继承自StatelessWidget,然后设置属性和事件,在build中绘制view以及事件的调用。

    一、自定义TextView

    1、重点,必须要传TextEditingController。

    import 'package:flutter/material.dart';
    
    /// 封装TextWidget
    class GHTextWidget extends StatelessWidget {
      /// 占位文字
      final String text;
    
      /// 点击事件
      final Object onChanged;
    
      /// 字号
      final double fontSize;
    
      /// 是否显示底部线条 默认显示
      final bool isShowBottomLine;
    
      final TextEditingController textEditingController;
    
      @override
      GHTextWidget(this.text,
          {Key key,
          this.onChanged = null,
          this.fontSize = 14,
          this.isShowBottomLine = true,
          this.textEditingController})
          : super(key: key);
    
      Widget build(BuildContext context) {
        return Container(
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
            width: 1,
            color:
                this.isShowBottomLine == true ? Colors.black12 : Colors.transparent,
          ))),
          height: 50,
          child: TextField(
              controller: this.textEditingController,
              style: TextStyle(
                fontSize: this.fontSize,
              ),
              onChanged: this.onChanged,
              decoration: InputDecoration(
                suffixIcon: InkWell(
                  onTap: () {
                    WidgetsBinding.instance.addPostFrameCallback(
                        (_) => this.textEditingController.text = "");
                  },
                  child: Icon(
                    (Icons.clear),
                    color:Colors.red,
                  ),
                ),
                contentPadding: EdgeInsets.only(left: 0, top: 0),
                hintText: this.text,
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(30),
                    borderSide: BorderSide.none),
              )),
        );
      }
    }
    

    2、调用方式

    TextEditingController _nameController = new TextEditingController();
    
     Container(
                      child: GHTextWidget(
                        "收件人姓名",
                        textEditingController: _nameController,
                      ),
                    ),
    

    点击调用,获取内容

      _addAddress(BuildContext context) {
        var url =
            "https://a4cj1hm5.api.lncld.net/1.1/classes/shopAddress";
        Map<String, dynamic> params ={
          'name':this._nameController.text,
          'phoneNumber':this._phoneNumberController.text,
          'province':this._province,
          'city':this._city,
          'area':this._area,
          'detailsAddress':this._detailsAddressController.text,
        };
        print(params);
        HttpRequest.request(url, method: 'POST',params:params).then((value) {
          var objectId = value["objectId"];
          if (objectId != null) {
            GHToast.showTost("添加地址成功");
            Navigator.pop(context);
          }
        });
      }
    
    image.png

    二、自定义UIButton

    
    class GHButton extends StatelessWidget {
      /// 背景颜色
      final Color backGroudColor;
    
      /// 标题
      final String title;
    
      /// 点击事件
      final Object tapAction;
    
      @override
      GHButton(this.title,
          {Key key, this.tapAction, this.backGroudColor = Colors.red})
          : super(key: key);
    
      Widget build(BuildContext context) {
        return Container(
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8), color: Colors.red),
          height: 50,
          child: TextButton(
            onPressed: this.tapAction,
            child: Text(
              this.title,
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
          ),
        );
      }
    }
    

    调用

     Container(
          child: GHButton(
                "确定",
                 tapAction: () {
                       _contentFocusNode.unfocus();
                      if(this._checkAddress()) {
                           this._addAddress(context);
                       }
                    },
            ),
       )
    

    二、自定义cell

    有两种方式传递事件,一种是使用我们自定义事件tapAction,另外的一种方法是使用EventBus来发送事件,监听事件的执行。从连贯性上来说还是我们自定义的tapAction比较好用,具有连贯的调用。但是如果是隔了几个widget,还是用EventBus方便,相当于通知,避免了较长的调用链。

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:ghome_project/services/EventBus.dart';
    import 'package:ghome_project/widget/GHButton.dart';
    
    class GHCell extends StatelessWidget{
      final Icons ;
      final String  title;
      final Object tapAction;
      GHCell(this.title, this.Icons,
          {Key key, this.tapAction})
          : super(key: key);
      @override
      Widget build(BuildContext context) {
        return Container(
          color: Colors.white,
          height: 50,
          child: Row(
            children: [
              SizedBox(width: 15),
              GestureDetector(
                child: Icon(
                  Icons,
                  color: Colors.red,
                ),
                  //第一种方法
                  onTap: this.tapAction,
                //第二种方法EventBus
                // onTap: (){
                //   eventBus.fire(LoginSuccessEvent('myBuy'));
                // },
    
              ),
              SizedBox(width: 10),
              Text(title),
            ],
          ),
        );
      }
    }
    

    调用方法:
    1、GHCell事件属性的调用

     GHCell(
                      '我的自定义view购买',
                      Icons.stop_circle_outlined,
                      tapAction: (){
                         print("点击了我的购买view");
                  }),
    

    2、EventBus的调用

      @override
      void initState() {
        super.initState();
        this.actionEventBus = eventBus.on<LoginSuccessEvent>().listen((event) {
          if(event.str == 'myBuy'){//myBuy购买事件处理
            print('eventBus监听到了myBuy事件');
          }
        });
      }
    

    相关文章

      网友评论

          本文标题:Flutter自定义View

          本文链接:https://www.haomeiwen.com/subject/dbmrwrtx.html