Как создать функциональные кнопки во флаттере? - PullRequest
0 голосов
/ 19 июня 2020

Я новичок в флаттере и пытаюсь создать функциональный калькулятор. Я правильно понял макет. Однако по какой-то причине я не могу изменить состояние своего main.dart, когда нажимаю кнопки и прошу приложение выполнить некоторые операции. Я создал отдельный класс для своих кнопок и вызываю их в main.dart с помощью Buttons button = Buttons ();

 import 'package:flutter/material.dart';
import 'button.dart';

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

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Center(
            child: Text(
              'CALCULATOR',
              style: TextStyle(fontSize: 25.0),
            ),
          ),
        ),
        body: ButtonsBuild(),
      ),
    );
  }
}

Button button = Button();
//We have now created a local variable to store the properties of Button into button. So we can now use its properties in main.dart

class ButtonsBuild extends StatefulWidget {
  @override
  _ButtonsBuildState createState() => _ButtonsBuildState();
}

class _ButtonsBuildState extends State<ButtonsBuild> {
  Widget buildButton(String buttonText) {
    return Padding(
      padding: const EdgeInsets.all(7.4),
      child: FlatButton(
        onPressed: () {
          setState(
            () {
              return button.buttonPressed(buttonText);
            },
          );

        },
        child: Text(
          '$buttonText',
          style: TextStyle(
              fontSize: 30.0,
              fontStyle: FontStyle.normal,
              color: Colors.grey[900]),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(15.0),
          child: Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Text(button.outPut
                    ,
                    style: TextStyle(fontSize: 45.0),
                  )
                ],
              ),
            ),
        ),
        Divider(
          height: 15.0,
        ),
        Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  child: Column(
                    children: <Widget>[
                      Row(
                        //button.buildButton is created coz build button is a property of a separate class that belongs to Button
                        children: <Widget>[
                          buildButton('.'),
                          buildButton('/'),
                          buildButton('*'),
                        ],
                      ),
                      Row(
                        children: <Widget>[
                          buildButton('7'),
                          buildButton('8'),
                          buildButton('9'),
                        ],
                      ),
                      Row(
                        children: <Widget>[
                          buildButton('4'),
                          buildButton('5'),
                          buildButton('6'),
                        ],
                      ),
                      Row(
                        children: <Widget>[
                          buildButton('1'),
                          buildButton('2'),
                          buildButton('3'),
                        ],
                      ),
                      Container(
                        width: 300,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: <Widget>[
                            Expanded(flex:2,
                              child: buildButton('0'),
                            ),
                            Expanded(child: buildButton('=')),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 320,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      buildButton('-'),
                      Expanded(flex: 2,
                        child: buildButton('+'),
                      ),
                      Expanded(
                        child: buildButton('C'),
                      ),
                    ],
                  ),
                )
              ],
            )
          ],
        )
      ],
    );
  }
}

Теперь в коде ниже я создал отдельный класс для моей кнопки import 'package: flutter / material.dart';

class Button {
  String buttonText;
  String outPut = '0';

  double num1 = 0.0;
  double num2 = 0.0;
  String operand = '';
  String outPutText = '0';

  Button({
    String buttonText,
    String outPut = '0',
    double num1 = 0.0,
    double num2 = 0.0,
    String operand = '',
    String outPutText = '0',
  }) {
    this.buttonText = buttonText;
    this.outPut = outPut;
    this.num1 = num1;
    this.num2 = num2;
    this.operand = operand;
    this.outPut = outPutText;
  }

  buttonPressed(String buttonText) {
    if (buttonText == 'C') {
      num1 = 0.0;
      num2 = 0.0;
      operand = '';
      outPutText = '0';
    } else if (buttonText == '+' ||
        buttonText == '-' ||
        buttonText == '/' ||
        buttonText == '*') {
      num1 = double.parse(outPut);
      operand = buttonText;
      outPutText = '0';
    } else if (buttonText == '.') {
      if (outPutText.contains('.')) {
        print('Already contains Decimal');
        return;
      } else {
        outPutText = outPutText + buttonText;
      }
    } else if (buttonText == '=') {
      num2 = double.parse(outPut);
      if (operand == '+') {
        outPutText = (num1 + num2).toString();
      }
      if (operand == '-') {
        outPutText = (num1 - num2).toString();
      }
      if (operand == '/') {
        outPutText = (num1 / num2).toString();
      }
      if (operand == '*') {
        outPutText = (num1 * num2).toString();
      }
      num1 = 00;
      num2 = 00;
      operand = '';

    } else {
      outPutText = outPutText = buttonText;
    }
    print(outPutText);
    // setState(() {
    //       outPut = double.parse(outPutText).toStringAsFixed(2);});
      }



      }
...