im new to dart/flutter, im trying to make a textfield that user can input index value and a button to submit it. For example, if user input 1 and click submit , then it will print apple. Thank you for helping. The error i get is String can't be assigned to a int, can i know how to fix this. Thank you.

Here is my source code

     import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fruity App'),
        ),
        body: MyWidget(),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  String _textString = 'Enter input to select your favourite fruit';
  String _select =
      '1 = Apple \n 2 = Pineapple \n 3 = Potato \n 4 = Orange \n 5 = Tomato';
  var fruitsIndex = 0;
  List<String> fruits = ['Apple', 'Pineapple', 'Potato', 'Orange', 'Tomato'];

  TextEditingController a = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextField(controller: a),
        Text(
          _textString,
          style: TextStyle(fontSize: 25),
        ),
        Text(
          _select,
          style: TextStyle(fontSize: 25),
        ),
        RaisedButton(child: Text('Submit'), onPressed: buttonPressed),
      ],
    );
  }

  void buttonPressed() {
    print(fruits[a.text.toString()]);
  }
}


Solution 1: Alberto Azinar

Try parsing that user input to int.

fruits[int.parse(a.text)]