Getter _text не определен для класса TagColumn во Flutter - PullRequest
1 голос
/ 01 мая 2020

Я смотрел на этот вопрос по переполнению стека Средство получения флаттера не указано для класса, когда оно указано . И я до сих пор не могу понять, почему мой класс Практика не имеет доступа к переменной _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 () , чтобы проверить, является ли текущий тег пустым при нажатии кнопки «плюс». Если нет, то создается новый тег.

enter image description here

1 Ответ

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

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,
      ),
    );
  }
}
...