2

When type "ab" like this then should display applebanana, enter image description here

Here it is my code enter image description here enter image description here

dola23
  • 87
  • 6

1 Answers1

2

Compare each character of the text of onChanged, and if it is the same as key of map, add value and setState to update the UI.

final map = {
    "a": "apple",
    "b": "banana",
    "p": "pineapple"
  };

  final controller = TextEditingController();

  @override
  void dispose() {
    // TODO: implement dispose
    controller.dispose();
    super.dispose();
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            TextField(
              onChanged: (String text){
                controller.text = "";
                for(int i=0; i<text.length; i++) {
                  if (i + 1 >= text.length) {
                    if (map[text[i]] != null) {
                      controller.text += map[text[i]]!;
                      print(controller.text);
                    }
                  }else{
                    if (map[text[i] + text[i + 1]] != null) {
                      controller.text += map[text[i] + text[i + 1]]!;
                      print(controller.text);
                    } else {
                      if (map[text[i]] != null) {
                        controller.text += map[text[i]]!;
                        print(controller.text);
                      }
                    }
                  }
                }
                setState(() {});
              },
            ),

            const SizedBox(height: 10),

            Text(controller.text != "" ? controller.text : ""),
          ],
        ),
      ),
    );
  }

enter image description here

Jungwon
  • 1,038
  • 7
  • 20
  • It's working! Thank you bro ! and also how to give if have map size is two or three then . Ex:- "bl": "blueberries","ch": "cherries", "b":"banana" – dola23 Sep 01 '22 at 06:29
  • @TharinduDasun It has been modified to be possible even when the length of the key value of the map is 1 or 2. – Jungwon Sep 01 '22 at 06:45