flutter 添加文本字段后出现白色屏幕

vom3gejh  于 2023-11-21  发布在  Flutter
关注(0)|答案(1)|浏览(180)

我有问题的UI在扑.我刚开始学习它.所以,我有一个计算器和数字系统转换器的应用程序,这是位于一个屏幕上.问题是,当我添加一个文本字段输入数字翻译到另一个数字系统,屏幕变成整个白色.

import 'package:flutter/material.dart';
import 'package:math_expressions/math_expressions.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.deepPurple)
            .copyWith(secondary: const Color.fromRGBO(184, 243, 215, 100)),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

//methods and consts
class _MyHomePageState extends State<MyHomePage> {
  List<String> buts = [
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "0",
    "+",
    "-",
    "/",
    "*",
    "=",
    "C"
  ];

//method for calculator
  double calculateExpression(String expression) {
    List<String> operators = expression
        .split(RegExp(r'[0-9.]'))
        .where((element) => element.isNotEmpty)
        .toList();
    List<String> numbers = expression.split(RegExp(r'[-+*/]'));
    List<String> expressions = [];

    for (int i = 0; i < numbers.length; i++) {
      expressions.add(numbers[i]);
      if (i < operators.length) {
        expressions.add(operators[i]);
      }
    }

    double result = double.parse(expressions[0]);

    for (int i = 1; i < expressions.length; i += 2) {
      if (expressions.contains("*") || expressions.contains("/")) {
        for (int i = 1; i < expressions.length; i += 2) {
          if (expressions[i] == "*" || expressions[i] == "/") {
            double leftOperand = double.parse(expressions[i - 1]);
            double rightOperand = double.parse(expressions[i + 1]);

            if (expressions[i] == "*") {
              expressions[i - 1] = (leftOperand * rightOperand).toString();
            } else if (expressions[i] == "/") {
              expressions[i - 1] = (leftOperand / rightOperand).toString();
            }

            expressions.removeAt(i);
            expressions.removeAt(i);
            i -= 2;
          }
        }
      }
      if (expressions[i] == "+") {
        result += double.parse(expressions[i + 1]);
      } else if (expressions[i] == "-") {
        result -= double.parse(expressions[i + 1]);
      }
    }

    return result;
  }

  String textFieldText = "";
  String currentOperator = "";
  double currentResult = 0;
  String selectedValue = "10s";
  String selectedValue1 = "10s";
  String conversionResult = "";

//method for converter
  String convertNumber(String number, String fromBase, String toBase) {
    int baseFrom = getBase(fromBase);
    int baseTo = getBase(toBase);

    try {
      int decimalValue = int.parse(number, radix: baseFrom);
      String result = decimalValue.toRadixString(baseTo);
      return result;
    } catch (e) {
      return 'error: $e';
    }
  }

  int getBase(String base) {
    switch (base.toLowerCase()) {
      case '2s':
        return 2;
      case '10s':
        return 10;
      case '16s':
        return 16;
      default:
        throw 'error: $base';
    }
  }

  void updateResult() {
    setState(() {
      conversionResult = convertNumber("42", selectedValue1, selectedValue);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: null,
      body: Column(
        children: <Widget>[
          //textfield for exp
          TextField(
            controller: TextEditingController(text: textFieldText),
            decoration: const InputDecoration(
              labelText: "Enter exp",
            ),
            style: const TextStyle(fontSize: 50.0),
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'[0-9=+\-*/]')),
            ],
          ),
          //calc buttons
          GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
            ),
            itemCount: 16,
            shrinkWrap: true,
            itemBuilder: (context, index) {
              return Container(
                decoration: BoxDecoration(
                  color: const Color.fromRGBO(184, 243, 215, 100),
                  border: Border.all(
                      color: const Color.fromRGBO(61, 84, 68, 100), width: 6.0),
                  borderRadius: const BorderRadius.all(Radius.circular(100.0)),
                ),
                child: InkWell(
                  onTap: () {
                    setState(() {
                      if (buts[index] == "=") {
                        if (currentOperator.isNotEmpty) {
                          String res =
                              "$currentResult$currentOperator$textFieldText";
                          Parser p = Parser();
                          Expression exp = p.parse(res);
                          ContextModel cm = ContextModel();
                          double result =
                              exp.evaluate(EvaluationType.REAL, cm);
                          textFieldText = result.toString();
                          currentResult = result;
                          currentOperator = "";
                        } else {
                          double res = calculateExpression(textFieldText);
                          textFieldText = res.toString();
                          currentResult = res;
                        }
                      } else if (buts[index] == "C") {
                        textFieldText = "";
                        currentResult = 0;
                        currentOperator = "";
                      } else {
                        if (index >= 0 && index <= 9) {
                          double digit = double.parse(buts[index]);
                          String digitString = digit.toString();
                          textFieldText += digitString;
                        } else {
                          textFieldText += currentOperator;
                          currentOperator = "";
                          textFieldText += buts[index];
                        }
                      }
                    });
                  },
                  child: Center(
                    child: Text(
                      buts[index],
                      style: const TextStyle(
                        color: Color.fromRGBO(51, 47, 44, 100),
                        fontSize: 60.0,
                      ),
                    ),
                  ),
                ),
              );
            },
          ),

          //row for converter
          Row(
            children: <Widget>[
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  //there must be textfield
                  DropdownButton<String>(
                    value: selectedValue1,
                    items: ["10s", "2s", "16s"]
                        .map((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                    onChanged: (String? newValue) {
                      setState(() {
                        selectedValue1 = newValue!;
                      });
                    },
                  ),
                ],
              ),
              const SizedBox(width: 25),
              Padding(
                padding: const EdgeInsets.only(top: 10),
                child: Container(
                  width: 60.0,
                  height: 50.0,
                  child: ElevatedButton(
                    onPressed: () {
                      updateResult();
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor:
                          const Color.fromRGBO(184, 243, 215, 100),
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0),
                        // Установите радиус равным нулю
                      ),
                    ),
                    child: const Text(
                      '=',
                      style: TextStyle(
                        fontSize: 25.0,
                      ),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 25),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    'Res: $conversionResult',
                    style: const TextStyle(fontSize: 30.0),
                  ),
                  DropdownButton<String>(
                    value: selectedValue,
                    items: ["10s", "2s", "16s"]
                        .map((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                    onChanged: (String? newValue) {
                      setState(() {
                        selectedValue = newValue!;
                      });
                    },
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }
}

字符串
如何添加textfield

Container(
            padding: const EdgeInsets.only(top: 20),
              child: Row(
                children: <Widget>[
                  Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    //added textfield
                    TextField(  
                      onChanged: (value) {
                      },
                      style: TextStyle(fontSize: 30.0),
                    ),
                    DropdownButton<String>(
                      value: selectedValue1,
                      items: ["10s", "2s", "16s"].map((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                      }).toList(),
                      onChanged: (String? newValue) {
                        setState(() {
                          selectedValue1 = newValue!;
                        });
                      },
                    ),
                  ],
                ),
                const SizedBox(width: 25),
                Padding(
                  padding: const EdgeInsets.only(top: 10),
                  child: Container(
                    width: 60.0,
                    height: 50.0,
                    child: ElevatedButton(
                      onPressed: () {
                        updateResult();
                      },
                      style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromRGBO(184, 243, 215, 100),
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0), // Установите радиус равным нулю
                      ),
                      ),
                      child: const Text(
                        '=',
                        style: TextStyle(
                          fontSize: 25.0,
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 25),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'Res: $conversionResult',
                      style: const TextStyle(fontSize: 30.0),
                    ),
                    DropdownButton<String>(
                      value: selectedValue,
                      items: ["10s", "2s", "16s"].map((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                      }).toList(),
                      onChanged: (String? newValue) {
                        setState(() {
                          selectedValue = newValue!;
                        });
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),

qni6mghb

qni6mghb1#

您可以在TextFiled将放置的行的子行上添加Expanded。错误是由无限约束宽度引起的。

Row(
  children: <Widget>[
    Expanded( //here expanded
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          //there must be textfield
          TextField(
            onChanged: (value) {},
            style: TextStyle(fontSize: 30.0),
          ),
          DropdownButton<String>(

字符串

相关问题