Flutter自定义登录输入框组件

316 阅读1分钟
import 'package:flutter/material.dart';
import 'package:xm_test_demo/utils/color.dart';

// 输入框封装
class LoginInput extends StatefulWidget {
  final String title;
  final String tip;
  final ValueChanged<String> onChanged;
  final ValueChanged<bool> focusChanged;
  TextInputType keyboardType;

  LoginInput(this.title, this.tip, this.onChanged, this.focusChanged,
      {this.keyboardType = TextInputType.phone});

  @override
  State<LoginInput> createState() => _LoginInputState();
}

class _LoginInputState extends State<LoginInput> {
  final _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // 获取光标的监听
    _focusNode.addListener(() {
      print("光标:== ${_focusNode.hasFocus}");
      if (widget.focusChanged != null) {
        widget.focusChanged(_focusNode.hasFocus);
      }
    });
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Row(
          children: [
            Container(
              padding: EdgeInsets.only(left: 20),
              width: 100,
              child: Text(
                widget.title,
                style: TextStyle(fontSize: 16),
              ),
            ),
            _input(), // 输入框
          ],
        ),
        Divider(
          // 横线
          height: 0, // 横线距离上个组件的间隙
          thickness: 1, // 横线粗细
          indent: 20, // 横线距离左边的间隙
        )
      ],
    );
  }

  // 输入框
  _input() {
    return Expanded(
        // Expanded 可以填充row剩余的空间
        child: TextField(
      focusNode: _focusNode,
      onChanged: this.widget.onChanged,
      keyboardType: widget.keyboardType,
      cursorColor: primayColor, // 光标颜色
      style: TextStyle(
          color: Colors.green, fontSize: 16, fontWeight: FontWeight.normal),
      decoration: InputDecoration(
          contentPadding: EdgeInsets.only(left: 0, right: 20),
          border: InputBorder.none,
          hintText: widget.tip ?? "",
          hintStyle: TextStyle(
              color: Colors.grey, fontSize: 14, fontWeight: FontWeight.normal)),
    ));
  }
}

/*
使用案例:
LoginInput(
        "用户名",
        "请输入用户名",
        (text) {
          print("输入的==$text");
        },
        (focus) {
          print("焦点==$focus");
        },
        keyboardType: TextInputType.text,
      ),
 */
```