Как получить значение из нескольких текстовых полей, созданных одним методом во флаттере? - PullRequest
2 голосов
/ 01 мая 2020

Я создал несколько текстовых полей, используя один метод в другом файле, как я получаю значение из них. Я хочу получить значение в разных переменных.

//class method

class CustomTextField {
  static TextField display(BuildContext context, [String name, double size=16,IconData icon]) {
    return new TextField(
      textAlign: TextAlign.center,
      style: CustomTextStyle.display(context, Colors.black38, size),
      decoration: new InputDecoration(
        alignLabelWithHint: true,
        icon: new Icon(icon),
        contentPadding:EdgeInsets.only(top: 30,right: 30,),
        border: InputBorder.none,
        hintText:"$name",
        focusedBorder: InputBorder.none,
        hintStyle: CustomTextStyle.display(context, Colors.grey, size),
      ),
    );
  }
}

//call method

 new Container(
          width: width,
          height: height,
          decoration: new BoxDecoration(
            borderRadius: new BorderRadius.all(Radius.circular(20)),
            gradient: new LinearGradient(
              colors: [
                Color.fromRGBO(252, 191, 93, 1),
                Color.fromRGBO(255, 210, 119, 1),
                Color.fromRGBO(252, 215, 85, 1),
              ],
              begin: Alignment.bottomCenter,
              end: Alignment.topCenter,
            ),
          ),
          child: CustomTextField.display(context, name,16,icon),
        ),

Ответы [ 4 ]

1 голос
/ 01 мая 2020

Прежде всего, я рекомендую вам использовать виджет без состояния для создания TextField вместо использования функции stati c, как показано ниже:

class CustomTextField extends StatelessWidget {
  final Function(String) onChanged;
  final String name;
  final double size;
  final IconData icon;

  CustomTextField({
    this.onChanged,
    this.name,
    this.size: 16,
    this.icon,
  });

  Widget build(BuildContext context) {
    return new TextField(
      textAlign: TextAlign.center,
      onChanged: onChanged,
      style: CustomTextStyle.display(context, Colors.black38, size),
      decoration: new InputDecoration(
        alignLabelWithHint: true,
        icon: new Icon(icon),
        contentPadding: EdgeInsets.only(
          top: 30,
          right: 30,
        ),
        border: InputBorder.none,
        hintText: "$name",
        focusedBorder: InputBorder.none,
        hintStyle: CustomTextStyle.display(context, Colors.grey, size),
      ),
    );
  }
}

Затем создайте функцию для onChange поле для получения нового значения:

class App extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: width,
        height: height,
        decoration: new BoxDecoration(
          borderRadius: new BorderRadius.all(Radius.circular(20)),
          gradient: new LinearGradient(
            colors: [
              Color.fromRGBO(252, 191, 93, 1),
              Color.fromRGBO(255, 210, 119, 1),
              Color.fromRGBO(252, 215, 85, 1),
            ],
            begin: Alignment.bottomCenter,
            end: Alignment.topCenter,
          ),
        ),
        child: CustomTextField(
          // Here you get the value change
          onChanged: (value) {
            print('Text value changed');
            print('New value: $value');
          },
          name: name,
          size: 16,
          icon: icon,
        ),
      ),
    );
  }
}
0 голосов
/ 01 мая 2020

Укажите TextEditingController в качестве параметра для построения вашего CustomTextField.

0 голосов
/ 01 мая 2020

Используйте функцию в качестве параметра для CustomTextField и добавьте его к параметру onChanged TextField;

class CustomTextField {
  static TextField display(BuildContext context, Function onChanged,
      [String name, double size = 16, IconData icon]) {
    return new TextField(
      textAlign: TextAlign.center,
      onChanged: onChanged,
      style: CustomTextStyle.display(context, Colors.black38, size),
      decoration: new InputDecoration(
        alignLabelWithHint: true,
        icon: new Icon(icon),
        contentPadding: EdgeInsets.only(
          top: 30,
          right: 30,
        ),
        border: InputBorder.none,
        hintText: "$name",
        focusedBorder: InputBorder.none,
        hintStyle: CustomTextStyle.display(context, Colors.grey, size),
      ),
    );
  }
}

, затем получите свое значение;

CustomTextField.display(
  context,
  (value) {
    print(value);
  },
  name,
  16,
  icon,
),
0 голосов
/ 01 мая 2020

вы должны предоставить функцию для обработки свойства onChange вашего пользовательского текстового поля.

вот как я использовал один в моем проекте:

пользовательский виджет класса

class MyTextField extends StatefulWidget {
  final String title;
  final Function onChange; // you can get the value from this function
  final bool isPassword;

  MyTextField(this.title, this.onChange, {this.isPassword = false});

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

class _MyTextFieldState extends State<MyTextField> {
  bool showPassword = false;
  final _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    _controller.addListener(() {
      setState(() {});
    });
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            widget.title,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 15,
            ),
          ),
          SizedBox(height: 2),
          TextField(
            controller: _controller,
            onChanged: widget.onChange,
            obscureText: !showPassword && widget.isPassword,
            decoration: InputDecoration(
                suffixIcon: widget.isPassword
                    ? IconButton(
                        icon: Icon(
                          Icons.remove_red_eye,
                          color: showPassword ? Colors.blue : Colors.grey,
                        ),
                        onPressed: () {
                          setState(() => showPassword = !showPassword);
                        },
                      )
                    : IconButton(
                        icon: Icon(
                          Icons.clear,
                          color: _controller.text.isEmpty
                              ? Colors.grey
                              : Colors.blue,
                        ),
                        onPressed: () => _controller.clear()),
                border: InputBorder.none,
                fillColor: Color(0xfff3f3f4),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.blue, width: 5.0),
                ),
                filled: true),
          )
        ],
      ),
    );
  }

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

вариант использования:

 MyTextField('Email', (value) => email = value.trim()), // body of onChange
            MyTextField(
              'Password',
              (value) => password = value.trim(), // body of onChange
              isPassword: true,
            ),
// value is what you get from the text fields.
...