Only static members can be accessed in initializers on TextEditingController

63 Views Asked by At

GOAL: when editing information it goes to a Form that has an initial value equal to the information at present.

The code below works because it has the property 'initialValue'

TextFormField(
   maxLines: 1,
   autofocus: true,
   initialValue: _currentProditem.producttitle,
   style: TextStyle(
            color: Colors.black87,
            fontWeight: FontWeight.w400,
            fontSize: 18.0,
            fontFamily:'Cabin',
          ),

but the code below does not work because the properties 'initialValue' and 'controller' are conflicting. That's why I commented the property 'initialValue' in the code below. But I want to put the initialValue somewhere so I can achieve the above goal.

TextFormField(
          controller: _controller,
          maxLines: 1,
          autofocus: true,
          // initialValue: _currentProditem.price,
          keyboardType: TextInputType.number,
          onChanged: (string) {
            string = '${_formatNumber(string.replaceAll(',', ''))}';
            _controller.text = string;
            Timer(Duration(milliseconds: 1), () {
              _controller.selection = TextSelection.fromPosition(TextPosition(offset: string.length));
            });
          },

so I researched how to put IntialValue and found that you need to add the code below

final _controller = TextEditingController(text: 'some text');

I tried changing the the word 'some text' to '_currentProditem.price' but there was a problem with the word '_currentProditem' it says 'error: Only static members can be accessed in initializers.'

For reference the word '_currentProditem' can be found on the code below

class ItemNotifier with ChangeNotifier {
  List<Proditem> _itemList = [];
  Proditem _currentProditem;

  UnmodifiableListView<Proditem> get itemList => UnmodifiableListView(_itemList);

  Proditem get currentProditem => _currentProditem;

  set itemList(List<Proditem> itemList) {
    _itemList = itemList;
    notifyListeners();
  }

  set currentProditem(Proditem proditem) {
    _currentProditem = proditem;
    notifyListeners();
  }
}
1

There are 1 best solutions below

1
On BEST ANSWER

only static fields can be accessed outside any method

so, just initialise the _controller empty

final _controller = TextEditingController();

while building or in initState set the value

_controller.text = currentPrice;

as the controller has a setter named text, its easy to update the value dynamically like when a button is pressed