Home > OS >  How to show Button Value in TextField in Flutter?
How to show Button Value in TextField in Flutter?

Time:06-20

I am trying to make a phone app clone using flutter, I want to show the values of the button on the textfield, that is if someone presses one textfield should show 1 and then if someone presses 2, the output on textfield should be 12.

This is the keypad file in which I want to show the output at the top.

import 'package:phoneapp/contacts.dart';
import 'package:phoneapp/favorites.dart';
import 'package:phoneapp/recents.dart';
import 'package:phoneapp/voicemail.dart';

import 'button.dart';

class Keypad extends StatefulWidget {
  const Keypad({Key? key}) : super(key: key);

  @override
  State<Keypad> createState() => _KeypadState();
}

class _KeypadState extends State<Keypad> {
  int currentindex = 3;
  final screens = [
    const Favorites(),
    const Recents(),
    const Contacts(),
    const Keypad(),
    const Voicemail()
  ];

  

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: currentindex == 3
            ? Column(
                children: [
                  const TextField(
                    textAlign: TextAlign.center,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                    ),
                  ),
                  const Padding(padding: EdgeInsets.all(10)),
                  const Text(
                    "Add Number",
                    style: TextStyle(color: Colors.blue),
                  ),
                  const Padding(
                    padding: EdgeInsets.all(15),
                  ),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: const [
                          Elevetedbutton(
                            text1: "1",
                            text2: "",
                          ),
                          Elevetedbutton(
                            text1: "2",
                            text2: "ABC",
                          ),
                          Elevetedbutton(
                            text1: "3",
                            text2: "DEF",
                          ),
                        ],
                      ),
                      const Padding(
                        padding: EdgeInsets.all(15),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: const [
                          Elevetedbutton(
                            text1: "4",
                            text2: "GHI",
                          ),
                          Elevetedbutton(
                            text1: "5",
                            text2: "JKL",
                          ),
                          Elevetedbutton(
                            text1: "6",
                            text2: "MNO",
                          ),
                        ],
                      ),
                      const Padding(
                        padding: EdgeInsets.all(15),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: const [
                          Elevetedbutton(
                            text1: "7",
                            text2: "PQRS",
                          ),
                          Elevetedbutton(
                            text1: "8",
                            text2: "TUV",
                          ),
                          Elevetedbutton(
                            text1: "9",
                            text2: "WXYZ",
                          ),
                        ],
                      ),
                      const Padding(
                        padding: EdgeInsets.all(15),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: const [
                          Elevetedbutton(
                            text1: "*",
                            text2: "",
                          ),
                          Elevetedbutton(
                            text1: "0",
                            text2: " ",
                          ),
                          Elevetedbutton(
                            text1: "#",
                            text2: "",
                          ),
                        ],
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 30,
                  ),
                  ElevatedButton(
                    onPressed: () {},
                    style: ElevatedButton.styleFrom(
                      primary: Colors.green,
                      fixedSize: const Size(70, 70),
                      shape: const CircleBorder(),
                      surfaceTintColor: Colors.grey,
                    ),
                    child: const Icon(Icons.phone),
                  ),
                  const Padding(
                    padding: EdgeInsets.all(15),
                  ),
                ],
              )
            : screens[currentindex],
      ),
      bottomNavigationBar: BottomNavigationBar(
        iconSize: 30,
        //selectedfontsize
        //unselectedfontsize
        showSelectedLabels: false,
        showUnselectedLabels: false,
        type: BottomNavigationBarType.fixed,
        currentIndex: currentindex,
        onTap: (index) => setState(() => currentindex = index),
        backgroundColor: Colors.black,
        selectedItemColor: Colors.blue,
        unselectedItemColor: Colors.white,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.star),
            label: "",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.time_to_leave),
            label: "",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.contacts),
            label: "",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.dialpad),
            label: "",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.voicemail),
            label: "",
          ),
        ],
      ),
    );
  }
}

This is the button.dart file which contains the widget ElevatedButton.

import 'package:flutter/material.dart';

class Elevetedbutton extends StatelessWidget {
  final String text1;
  final String text2;
  const Elevetedbutton({Key? key, required this.text1, required this.text2})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {},
      style: ElevatedButton.styleFrom(
        primary: Colors.grey,
        fixedSize: const Size(80, 80),
        shape: const CircleBorder(),
        surfaceTintColor: Colors.grey,
      ),
      child: Column(
        children: [
          Padding(padding: EdgeInsets.all(3)),
          Text(
            text1,
            style: TextStyle(fontSize: 30),
          ),
          Text(text2),
        ],
      ),
    );
  }
}

CodePudding user response:

First, you need to add a TextController to your textfield.

Then, you need to add another parameter to your Elevetedbutton class. It is to pass the onPressed button function.

Next, you just need to keep adding text to the first text controller whenever you press a button in numpad.

At last, you need a function so that your cursor moves to the end of the number length.

I ran your code and edited the code for you. Now, when your press '1''2''3', you'll see your textfield is showing the numbers. Please follow my implementation from on pressed functions from buttons 1 2 & 3 into your other buttons. Check the below code for implementation:

class Keypad extends StatefulWidget {
  const Keypad({Key? key}) : super(key: key);

  @override
  State<Keypad> createState() => _KeypadState();
}

class _KeypadState extends State<Keypad> {
  int currentindex = 3;
  final screens = [
     Container(),
    Container(),
    Container(),
    const Keypad(),
    Container()
  ];

  TextEditingController _textEditingController = TextEditingController(); //<----- added this

  void moveTextCursorPosition() {
    _textEditingController.selection = TextSelection(
        baseOffset: _textEditingController.text.length,
        extentOffset: _textEditingController.text.length);
  } //<--- added this function to move cursor to end of text

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: currentindex == 3
            ? Column(
          children: [
             TextField(
              controller: _textEditingController,
              autofocus: true,
              textAlign: TextAlign.center,
              decoration: const InputDecoration(
                border: InputBorder.none,
              ),
            ),
            const Padding(padding: EdgeInsets.all(10)),
            const Text(
              "Add Number",
              style: TextStyle(color: Colors.blue),
            ),
            const Padding(
              padding: EdgeInsets.all(15),
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children:  [
                    Elevetedbutton(
                      text1: "1",
                      text2: "",
                      onPressed: () {
                        _textEditingController.text = _textEditingController.text   '1';
                        moveTextCursorPosition();
                      }, //<---- you need this function in all numbers 
                    ),
                    Elevetedbutton(
                      text1: "2",
                      text2: "ABC",
                      onPressed: () {
                        _textEditingController.text = _textEditingController.text   '2';
                        moveTextCursorPosition();
                      },
                    ),
                    Elevetedbutton(
                      text1: "3",
                      text2: "DEF",
                      onPressed: () {
                        _textEditingController.text = _textEditingController.text   '3';
                        moveTextCursorPosition();
                      },
                    ),
                  ],
                ),
                const Padding(
                  padding: EdgeInsets.all(15),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Elevetedbutton(
                      text1: "4",
                      text2: "GHI",
                      onPressed: () {
                        print('4');
                      },
                    ),
                    Elevetedbutton(
                      text1: "5",
                      text2: "JKL",
                      onPressed: () {
                        print('5');
                      },
                    ),
                    Elevetedbutton(
                      text1: "6",
                      text2: "MNO",
                      onPressed: () {
                        print('1');
                      },
                    ),
                  ],
                ),
                const Padding(
                  padding: EdgeInsets.all(15),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children:  [
                    Elevetedbutton(
                      text1: "7",
                      text2: "PQRS",
                      onPressed: () {
                        print('1');
                      },
                    ),
                    Elevetedbutton(
                      text1: "8",
                      text2: "TUV",
                      onPressed: () {
                        print('1');
                      },
                    ),
                    Elevetedbutton(
                      text1: "9",
                      text2: "WXYZ",
                      onPressed: () {
                        print('1');
                      },
                    ),
                  ],
                ),
                const Padding(
                  padding: EdgeInsets.all(15),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children:  [
                    Elevetedbutton(
                      text1: "*",
                      text2: "",
                      onPressed: () {
                        print('1');
                      },
                    ),
                    Elevetedbutton(
                      text1: "0",
                      text2: " ",
                      onPressed: () {
                        print('1');
                      },
                    ),
                    Elevetedbutton(
                      text1: "#",
                      text2: "",
                      onPressed: () {
                        print('1');
                      },
                    ),
                  ],
                ),
              ],
            ),
            // const SizedBox(
            //   height: 30,
            // ),
            ElevatedButton(
              onPressed: () {},
              style: ElevatedButton.styleFrom(
                primary: Colors.green,
                fixedSize: const Size(70, 70),
                shape: const CircleBorder(),
              ),
              child: const Icon(Icons.phone),
            ),
            const Padding(
              padding: EdgeInsets.all(15),
            ),
          ],
        )
            : screens[currentindex],
      ),
      bottomNavigationBar: BottomNavigationBar(
        iconSize: 30,
        //selectedfontsize
        //unselectedfontsize
        showSelectedLabels: false,
        showUnselectedLabels: false,
        type: BottomNavigationBarType.fixed,
        currentIndex: currentindex,
        onTap: (index) => setState(() => currentindex = index),
        backgroundColor: Colors.black,
        selectedItemColor: Colors.blue,
        unselectedItemColor: Colors.white,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.star),
            label: "",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.time_to_leave),
            label: "",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.contacts),
            label: "",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.dialpad),
            label: "",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.voicemail),
            label: "",
          ),
        ],
      ),
    );
  }
}

class Elevetedbutton extends StatelessWidget {
  final String text1;
  final String text2;
  final Function onPressed;  //added this to your elevated button class
  const Elevetedbutton({Key? key, required this.text1, required this.text2, required this.onPressed})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        onPressed();
      },
      style: ElevatedButton.styleFrom(
        primary: Colors.grey,
        fixedSize: const Size(80, 80),
        shape: const CircleBorder(),
      ),
      child: Column(
        children: [
          Padding(padding: EdgeInsets.all(3)),
          Text(
            text1,
            style: TextStyle(fontSize: 30),
          ),
          Text(text2),
        ],
      ),
    );
  }
}

CodePudding user response:

Add a controller to the textfield and update it value when the button is pressed

like this in the widget class

TextEditingController value = TextEditingController();

and give the constructor to the textfield

Textfield( controller : value
.....

and change its value on button pressed like this

onPressed :(){
value.text = num;
}

and it will be automatically updated

CodePudding user response:

first of all, add a controller to the TextField() lets say

TextEditingController controller = TextEditingController();

And add this to TextField(controller: controller)

Now for tap of each button you need to change the value of the controller. So let's make a function for it.

void addValue(int value){
  String currentValue = controller.text; // getting current value of textfield
  String newValue = currentValue (value.toString());         //adding new value to the end of previous value(string) using concatenation.
  setState((){
    controller.text = newValue;     ///setting new value as data in TextField})
});
  • Related