首页 > 解决方案 > 如何使用另一个类的 TextEditingController()

问题描述

我有这个代码:

final _text = TextEditingController();

Widget _formatoCampo(String str_campo, Icon icon_campo) {
return TextField(
  controller: _text,
  onChanged: (text) {
    setState(() {});
  },
  autofocus: true,
  decoration: InputDecoration(
    filled: true,
    fillColor: Colors.white,
    focusedBorder: OutlineInputBorder(
      borderSide: BorderSide(color: Colors.red[100]),
      borderRadius: BorderRadius.circular(25.7),
    ),
    hintText: str_campo,
    suffixIcon: IconButton(
      icon: icon_campo,
    ),
  ),
);

}

我用来构建一个小部件,这个:

Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
return Scaffold(
  body: Container(
    height: height,
    decoration: BoxDecoration(
        gradient: RadialGradient(
            radius: 0.7, colors: [Colors.red[100], Colors.white])),
    child: Stack(
      children: <Widget>[
        Positioned(
          top: -MediaQuery.of(context).size.height * .15,
          right: -MediaQuery.of(context).size.width * .4,
          child: BezierContainer(),
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 20),
          child: Column(
            children: [
              SizedBox(height: height * .1),
              titulo(),
              Expanded(
                child: Container(
                  margin: const EdgeInsets.all(8.0),
                  padding: const EdgeInsets.all(3.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      _formatoCampo('Introduzca su nombre y apellido',
                          Icon(Icons.accessibility_new_sharp)),
                      _separadores(height),
                      _formatoDescripcion(
                          'Con este nombre se te identificará al momento de realizar los pedidos'),
                    ],
                  ),
                ),
              ),
              ButtonElevationWithIcon(
                enable: _text.text != '' ? true : false,
                buttonText: 'Siguiente',
                onPressedButton: () {},
              ),
              _inicionsesionLabel(),
            ],
          ),
        ),
        Positioned(top: 40, left: 0, child: _atrasBoton()),
      ],
    ),
  ),
);

}

问题是我在其他屏幕上使用的这个小部件,我想将“_formatoCampo”方法放在另一个类中,以便从多个地方调用它。如何将 TextEditingController() 作为参数以及 setState() 传递?

标签: flutterflutter-widget

解决方案


abstract class IsSilly {
  void makePeopleLaugh();
}

class Clown implements IsSilly {
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}

class Comedian implements IsSilly {
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}

使用 aAbstract Class定义您的方法。然后您可以执行此操作。


推荐阅读