Getter _text не определен для класса TagColumn во Flutter

Я рассмотрел этот вопрос о переполнении стека Flutter геттер не указан для класса, если он указан. И я до сих пор не могу понять, почему мой класс Практика не имеет доступа к переменной _text, доступ к которой осуществляется из элемента в Списке с типом TagColumn. .

class Practice extends StatefulWidget {
  @override
  _PracticeState createState() => _PracticeState();
}

class _PracticeState extends State<Practice>{
  int count  = 0;

  @override
  Widget build(BuildContext context){
    List<TagColumn> ok = List.generate(count, (int i) => new TagColumn());
    return Scaffold(
      backgroundColor: Colors.black,
      body: new LayoutBuilder(builder: (context, constraint){
      return new Stack(
        children: <Widget>[
          SingleChildScrollView(
            child: SafeArea(
              child: new Wrap(
                direction: Axis.horizontal,
                children: ok,
              )
            ),
          ),
          new Positioned(
            child: new Align(
              alignment: FractionalOffset.bottomRight,
              child: Container(
                margin: EdgeInsets.only(bottom: 50.0, right: 40.0),
                child: RawMaterialButton(
                  onPressed: (){
                    setState(() {
                      if(count != 0 && ok[count]._text.text.isEmpty){

                      }
                      else{
                          count +=1;
                      }
                    });
                  },
                  shape: CircleBorder(),
                  child: Icon(
                    Icons.add_circle,
                    size: 100.0,
                    color: Color(0xffd3d3d3),
                  ),
                )
              )
            )
          )

        ],
      );
      }),
    );
  }
}

class TagColumn extends StatefulWidget{
  @override
  State<StatefulWidget> createState() => new _TagColumn();
}

class _TagColumn extends State<TagColumn>{
  final _text = TextEditingController();
  bool _validate = false;

  @override

  Widget build(BuildContext context){
    final tagField = TextField(
      controller: _text,
      obscureText: false,
      style: TextStyle(fontFamily: 'Play', color: Colors.white, fontSize: 20),
      maxLines: null,
      keyboardType: TextInputType.text,
      decoration: InputDecoration(
        contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
        hintText: "Tag",
          errorText: _validate ? 'Value Can\'t be Empty': null,
          border:
          OutlineInputBorder(borderRadius: BorderRadius.circular(32.0))),
      );
    return Container(
      width: MediaQuery.of(context).size.width/2 - 40,
      margin: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      decoration: BoxDecoration(
        color: Colors.blue,
        borderRadius: BorderRadius.circular(32.0),
      ),
      child: Theme(
        data: ThemeData(
          hintColor: Colors.white,
        ),
        child: tagField,
      ),
    );
  }
}

Я пытаюсь не разрешить пользователю создавать новый тег при нажатии "Плюс" в правом нижнем углу (см. Изображение ниже), если пользователь не вводит текст в текущий. Другими словами, если он не пустой. Таким образом, я использую переменную final _text = TextEditingController (), чтобы проверить, пуст ли текущий тег при нажатии кнопки «плюс». В противном случае создается новый тег.

введите здесь описание изображения


person Ashu Mundra    schedule 01.05.2020    source источник


Ответы (1)


dart рассматривает переменные, которые начинаются с подчеркивания, как частную переменную (поскольку в dart нет частного ключевого слова), поэтому для решения вашей проблемы вам необходимо удалить _ (подчеркивание) перед текстовой переменной.

что плохого в этом

1- переместите переменную _text в класс TagColumn, вставленный в класс State

class TagColumn extends StatefulWidget{
 final text = TextEditingController(); // removed the _ so that to access it inside the Practise class
  @override
  State<StatefulWidget> createState() => new _TagColumn();
}

и обновите класс TagColumn, чтобы отразить эти изменения.


class _TagColumn extends State<TagColumn>{
   // final _text = TextEditingController(); <---- since the text is now in the TagColumn class not the state class
  bool _validate = false;

  @override

  Widget build(BuildContext context){
    final tagField = TextField(
      controller: widget.text,
      obscureText: false,
      style: TextStyle(fontFamily: 'Play', color: Colors.white, fontSize: 20),
      maxLines: null,
      keyboardType: TextInputType.text,
      decoration: InputDecoration(
        contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
        hintText: "Tag",
          errorText: _validate ? 'Value Can\'t be Empty': null,
          border:
          OutlineInputBorder(borderRadius: BorderRadius.circular(32.0))),
      );
    return Container(
      width: MediaQuery.of(context).size.width/2 - 40,
      margin: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      decoration: BoxDecoration(
        color: Colors.blue,
        borderRadius: BorderRadius.circular(32.0),
      ),
      child: Theme(
        data: ThemeData(
          hintColor: Colors.white,
        ),
        child: tagField,
      ),
    );
  }
}
person Ahmed Khattab    schedule 01.05.2020