组件Flutter中不需要变量

46qrfjad  于 2023-02-25  发布在  Flutter
关注(0)|答案(1)|浏览(158)

我的部件在Flutter时出了点问题。
我的组件代码:

import 'package:flutter/material.dart';

class MyTextField extends StatelessWidget {
  final controller;
  final String hintText;
  final bool obscureText;
  final Icon icon;

  const MyTextField({
    super.key,
    required this.controller,
    required this.hintText,
    required this.obscureText,
    required this.icon,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 25.0),
      child: TextField(
        controller: controller,
        obscureText: obscureText,
        decoration: InputDecoration(
            enabledBorder: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.white),
            ),
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.grey.shade400),
            ),
            fillColor: Colors.grey.shade200,
            filled: true,
            hintText: hintText,
            hintStyle: TextStyle(color: Colors.grey[500]),
          suffixIcon: icon,
        ),

      ),
    );
  }
}

正如你所看到的,我使用了一个图标变量,但我想使该变量不一定要使用,但万一我想把一个图标放在我的TextField的末尾,然后我可以这样做。问题是,当我在登录页面中使用我的组件时,如果我写这个,它会给我一个错误:

MyTextField(controller: emailController, hintText: 'Email', obscureText: false, icon: null),

我该怎么补救呢?先谢了

jhkqcmku

jhkqcmku1#

您正在指示该图标应该是必需的,它应该只是更改为它可以为空。

import 'package:flutter/material.dart';

class MyTextField extends StatelessWidget {
  final controller;
  final String hintText;
  final bool obscureText;
  final Icon? icon;

  const MyTextField({
    super.key,
    required this.controller,
    required this.hintText,
    required this.obscureText,
      this.icon,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 25.0),
      child: TextField(
        controller: controller,
        obscureText: obscureText,
        decoration: InputDecoration(
            enabledBorder: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.white),
            ),
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.grey.shade400),
            ),
            fillColor: Colors.grey.shade200,
            filled: true,
            hintText: hintText,
            hintStyle: TextStyle(color: Colors.grey[500]),
          suffixIcon: icon,
        ),

      ),
    );
  }
}

我的文本字段(控制器:电子邮件控制器,提示文本:"电子邮件",模糊文本:假),

相关问题