Вернуть значение String (s) и присвоить значение из TextField на Flutter - PullRequest
0 голосов
/ 05 мая 2020

Я создаю калькулятор гематрии, который присваивает номер букве в алфавитном порядке. У меня есть код ниже, и я хочу, чтобы каждая буква, введенная в TextField, возвращалась на нажатой плавающей кнопке, она уже возвращает введенное значение. Пытался добавить .toString () после _myController.text, но ничего не случилось. Понятия не имею, как это сделать. Посмотрите код.

class MyHomePage extends StatefulWidget {

  _MyHomePageState createState() => _MyHomePageState();

  @override
  Widget build(BuildContext context){
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        child:Column(
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: Padding(
                padding: const EdgeInsets.only(top: 60),
                child: Text('Decode your reality'.toUpperCase(),),
              ),
            ),
            Container(
              height:180,
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.only(top: 40, left: 30, right: 30, bottom: 40),
              child: TextField(
                decoration: InputDecoration(
                    labelText: 'Type a word or phrase',
                    fillColor: Colors.white70, filled: true,
                    ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _MyHomePageState extends State<MyHomePage> {

  String a = 1.toString();
  String b = 2.toString();
  String c = 3.toString();
  String d = 4.toString();
  String e = 5.toString();
  String f = 6.toString();
  String g = 7.toString();
  String h = 8.toString();
  String i = 9.toString();
  String j = 10.toString();

  //...up to 26

  final myController = TextEditingController();

  @override
  void dispose() {
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        child:Column(
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: Padding(
                padding: const EdgeInsets.only(top: 60),
                child: Text('Decode your reality'),
              ),
            ),
            Container(
              height:180,
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.only(top: 40, left: 30, right: 30, bottom: 40),
              child: TextField(
                controller: myController,
                decoration: InputDecoration(
                    labelText: 'Type a word or phrase',
                    fillColor: Colors.white70, filled: true,
                    border: new OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(10.0),
                      ),
                    ),
                    hintText: 'capital letters makes a diference'
                ),
              ),
            ),


    Container(
        child: FloatingActionButton(
          onPressed: () {
            return showDialog(
              context: context,
              builder: (context) {
                return Container(
                  height: MediaQuery.of(context).size.height/2,
                    margin: EdgeInsets.only(top: 200),
                    decoration: new BoxDecoration(
                      color: Colors.white
                    ),
                    child: Text( myController.text,
                      style: TextStyle(color: Colors.grey),
                  ),
                );
              },
            );
          },
          child: Icon(Icons.info),
        ),
    ),
    ],
      ),
    )
    );
  }
}

Заранее спасибо!

1 Ответ

0 голосов
/ 05 мая 2020

Если вы хотите, чтобы каждая буква возвращалась отдельно, вам нужно разделить слово, которое вводит пользователь, в прошлом я делал подобное приложение, я немного адаптировал код, чтобы помочь:

class MyHomePage extends StatefulWidget {
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  Map<String, int> alphabet = {
    'A': 1,
    'B': 2,
    'C': 3,
    'D': 4,
    'E': 5,
    'F': 6,                //a map that have numbers assigned to letters
    'G': 7,
    'H': 8,
    'I': 9,
    'J': 10,
    'K': 11,
    'L': 12,
    'M': 13,
    'N': 14,
    'O': 15,
    'P': 16,
    'Q': 17,
    'R': 18,
    'S': 19,
    'T': 20,
    'U': 21,
    'V': 22,
    'W': 23,
    'X': 24,
    'Y': 25,
    'Z': 26,
  };

  final myController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        child: Column(
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: Padding(
                padding: const EdgeInsets.only(top: 60),
                child: Text('Decode your reality'),
              ),
            ),
            Container(
              height: 180,
              width: MediaQuery.of(context).size.width,
              padding:
                  EdgeInsets.only(top: 40, left: 30, right: 30, bottom: 40),
              child: TextField(
                controller: myController,
                decoration: InputDecoration(
                    labelText: 'Type a word or phrase',
                    fillColor: Colors.white70,
                    filled: true,
                    border: new OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(10.0),
                      ),
                    ),
                    hintText: 'capital letters makes a diference'),
              ),
            ),
            Container(
              child: FloatingActionButton(
                onPressed: () {
                  return showDialog(
                    context: context,
                    builder: (context) {
                      return Container(
                        height: MediaQuery.of(context).size.height / 2,
                        margin: EdgeInsets.only(top: 200),
                        decoration: new BoxDecoration(color: Colors.white),
                        child: Text(
                          decodeLetters(),     //the function being called here
                          style: TextStyle(color: Colors.grey),
                        ),
                      );
                    },
                  );
                },
                child: Icon(Icons.info),
              ),
            ),
          ],
        ),
      ),
    );
  }

  String decodeLetters(){                         //and the function to transform the letters
    List<String> text = myController.text.split('');   //spliting the letters
    List<String> decodedText = [];

      for(int index = 0; index < text.length; index++){
        alphabet.forEach((letter, value){           //iterating the map and comparing to the letters
          if(letter == text[index].toUpperCase()){
              decodedText.add(value.toString());
          }
        });
      }
    return decodedText.toString();
  }

  @override
  void dispose() {
    myController.dispose();
    super.dispose();
  }

}
...