у меня есть три текстовых поля, я хочу выбрать между первыми двумя и работать с третьим, как это сделать, пожалуйста, руководство - PullRequest
0 голосов
/ 06 февраля 2020
import 'package:flutter/material.dart';

void main() => runApp(new CalculatorApp());

class CalculatorApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(title:'Bending Calculator',
      home: Calculator()
    );
  }
}

class Calculator extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => Calculatore();
}

class Calculatore extends State<Calculator> {
final a = TextEditingController();
  final b = TextEditingController();
  final c = TextEditingController();
// controller mentioned
 String total= "";

void calculate()  {
    int numberA = int.parse(a.text);
    int numberB = int.parse(b.text);
    int numberC = int.parse(c.text);
    int  result;
// if numberA have value then answer will be a+c


if( 
// what condition to do here for between choosing between  textfields a or b.
// i tried numberB ==null   that does not work
// very much confused, no idea what to do please help

){
result = numberA + numberC
} else{ result = numberB + numberC
}


    setState(() {
      total = "$result";
    });
  }
  @override
  Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title:Text("Calculator")),
        body: SafeArea(
            child: ListView(
              children: <Widget>[
                Row( mainAxisAlignment: MainAxisAlignment.center ,
                  children: <Widget>[

// первое текстовое поле

                    Container(width: MediaQuery.of(context).size.width *0.45 ,height: 50,
                       child: TextField(
                           controller: a,
                           decoration: InputDecoration(hintText: " Enter a value"),
                           keyboardType: TextInputType.number),
                    ),
                    Container(width: MediaQuery.of(context).size.width * 0.04,height: 50,),
// second textfield
                    Container(width: MediaQuery.of(context).size.width* 0.45,height: 50,
                      child: TextField(
                          controller: b,
                          decoration: InputDecoration(hintText: " Enter  b value"),
                          keyboardType: TextInputType.number),), ],
                ),

                Row(mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[

// третье текстовое поле

Контейнер (ширина: MediaQuery.of (context) .size.width * 0.9, высота: 50, child: TextField (контроллер: c, украшение: InputDecoration (hintText: «Enter c value»), keyboardType: TextInputType.number),),],), Row (mainAxisAlignment: MainAxisAlignment.center, потомки: [

// кнопка

                    RaisedButton(
                      onPressed: calculate,
                      child: Text('Calculate'),),
                  ],
                ),
                Text("   Total : $total", style: TextStyle(fontSize: 20.0),),
      ],
            ))
    );
  }
}

Ответы [ 3 ]

0 голосов
/ 06 февраля 2020

На основании вашего комментария это, возможно, должно помочь. Обычный int.parse выдаст ошибку, если текст, который вы предоставляете для разбора, пуст. Вместо этого используйте int.tryParse как в документации здесь . Это вернет null, если предоставленная строка пуста. Живая версия доступна в этом дартпад .

    int numberA = int.tryParse(a.text);
    int numberB = int.tryParse(b.text);
    int numberC = int.tryParse(c.text);
    int result;

    // if numberA have value then answer will be a+c

    // Note following conditions have order precedence. So only one of them execute.     
    if (numberA != null && numberC != null) {
      result = numberA + numberC;
    } else if (numberB != null && numberC != null){
      result = numberB + numberC;
    } 

Если вы хотите вычислить сумму при наличии всех трех полей. Используйте следующее условие.

    if (numberA != null && numberB != null && numberC != null) {
      result = numberA + numberB + numberC;
    } else if (numberA != null && numberC != null) {
      result = numberA + numberC;
    } else if (numberB != null && numberC != null){
      result = numberB + numberC;
    } 

То же самое можно сделать, проверив текст вместо проанализированного номера.

0 голосов
/ 06 февраля 2020

"" не может разобрать int. Вы можете использовать «try & catch» или «tryParese». Как насчет этого?

void calculate() {
  int numberA = int.tryParse(a.text);
  int numberB = int.tryParse(b.text);
  int numberC = int.tryParse(c.text);
  int result;

  if (numberB == null) {
    result = numberA + numberC;
  } else {
    result = numberB + numberC;
  }

  setState(() {
    total = "$result";
  });
}
0 голосов
/ 06 февраля 2020

Как я понимаю, вы пытались проверить, является ли значение текстового поля b нулевым. Вы пытались проверить, b.text.isEmpty или isNotEmpty.

...