Hoo
Hoo

Reputation: 1840

Display four textField

I want to have 4 textField in my app. In initState, it will fetch data from server, then put the text into textField.

List<TextEditingController> _controllers = [];
 
  @override
  void initState() {
    _controllers.add(TextEditingController());
    _controllers[0] = TextEditingController();
    _controllers[1] = TextEditingController();
    _controllers[2] = TextEditingController();
    _controllers[3] = TextEditingController();

    sharedPreferences.getUser().then((onValue) {

      _bloc
          .getData(...) // fetch from server
          .then((onValue) {
        for (int i = 0; i < onValue.esd.data.length; i++) {
          _controllers[i].text = onValue.esd.data['name'];
        }
        setState(() {});
      });
    });
    super.initState();
  }

Here the widget build

 Widget _showQueries() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
            ....
        ListView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: 4,
          itemBuilder: (context, index) {
            return Padding(
                padding: EdgeInsets.all(5),
                child: TextField(
                    maxLines: 2,
                    controller: _controllers[index],
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                          borderRadius: const BorderRadius.all(
                              const Radius.circular(5.0))),
                      contentPadding: EdgeInsets.all(10),
                    )));
          },
        )
      ],
    );
  }

Error

RangeError (index): Invalid value: Only valid value is 0: 1

Upvotes: 0

Views: 80

Answers (2)

Bishwajeet Parhi
Bishwajeet Parhi

Reputation: 48

You are getting this error due to your _controller var. At start when the widget was created, that variable contained an Empty List of type TextEditingController. Now when initstate was called, you added a TextEditingController to that list, but you have added only one controller not 4, and Dart haven't kept a count on that list during compile time so you are probably getting the error during runtime.

The possible fix might be instead of adding controllers in initState, just add the 4 controllers in that list.

List<TextEditingController> _controllers = [
TextEditingController(),
TextEditingController(),
TextEditingController(),
TextEditingController(),
];

Now you probably won't get a range error

Upvotes: 1

bhagavati antala
bhagavati antala

Reputation: 175

please let us know what response you are getting from the server in "onValue" this variable.

Upvotes: 0

Related Questions