如何在 Flutter 中使用我的 Text() 小部件中的值?

How can I use the value inside my Text() widget in flutter?

我正在研究一种 flutter 计数器,它随按钮增加而随另一个按钮减小,但问题是我不知道如何使用计数器的最终值,并且 save/grab 它有一个浮动操作按钮。

这是我的 Text() 小部件

Container(
              margin: EdgeInsets.zero,
              padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(3),
                  color: _counter != 0
                      ? widget.counterTextBackgroundColor
                      : Colors.grey[350]),
              child: Text(
                '$_counter',
                style: TextStyle(
                  fontSize: widget.counterTextSize,
                  color: widget.counterTextColor,
                ),
              ),
            ),

我尝试使用 TextField() 小部件,但它看起来很糟糕,它看起来太大了,其中一个问题是如果计数器为 0,我减少的 IconButton 不会显示,所以它会扩展更多,并且我也尝试过使用 FormTextField,同样的事情。

计数器用 TextField() 扩展

根据您的问题,我假设在按下按钮时,您希望在不使用文本框的情况下增加或减少文本的值。您所要做的就是在 SetState() 方法中增加计数器,如下所示-

floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
              //Enter the code you want to change here
              _counter=_counter+1;
            });
        },)

现在,在这段代码之外,您可以随时使用 _counter 变量来获取值。

有六个 Text 小部件,为此您需要使用六个计数器变量。在这种情况下我们可以使用List<int>

应用你的装饰。

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<int> _counters = List.filled(6, 0);

  List<String> titles = List.generate(6, (index) => "item $index");
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
        ...List.generate(
          titles.length,
          (index) => _item(
            index: index,
          ),
        )
      ],
    ));
  }

  Widget _item({
    Color background = Colors.red,
    required int index,
  }) =>
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          decoration: BoxDecoration(
              color: background, borderRadius: BorderRadius.circular(12)
              //....
              ),
          child: Row(
            children: [
              Text(titles[index]),
              Spacer(), // provide space
              IconButton(
                onPressed: () {
                  setState(() {
                    _counters[index]--;
                    if (_counters[index] <= 0) _counters[index] = 0;
                  });
                },
                icon: Icon(Icons.minimize),
              ),

              SizedBox(width: 12),
              Text(_counters[index].toString()), SizedBox(width: 12),
              IconButton(
                onPressed: () {
                  setState(() {
                    _counters[index]++;
                  });
                },
                icon: Icon(Icons.add),
              ),
            ],
          ),
        ),
      );
}

可以根据您的情况使用 TextEditingController,或者创建自定义控制器。

希望下面的完整代码对您和其他人(无异常管理)有所帮助:

import 'package:flutter/material.dart';

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

  @override
  State<FormControllerScreen> createState() => _FormControllerScreenState();
}

class _FormControllerScreenState extends State<FormControllerScreen> {
  TextEditingController ctrlOne = TextEditingController();
  TextEditingController ctrlTwo = TextEditingController();
  TextEditingController ctrlThree = TextEditingController();

  @override
  void initState() {
    ctrlOne.text = '0';
    ctrlTwo.text = '0';
    ctrlThree.text = '50';
    super.initState();
  }

  getStyleButtonStyle() {
    return ElevatedButton.styleFrom(
      padding: EdgeInsets.zero,
      minimumSize: const Size(20, 20),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          buildFormElement("controller one", 0, 5, 1, ctrlOne),
          buildFormElement("controller two", -5, 5, 1, ctrlTwo),
          buildFormElement("controller three", 50, 100, 10, ctrlThree),
          TextButton(onPressed: onSave, child: const Text("SAVE")),
        ],
      ),
    );
  }

  void onSave() {
    print("controller one:   " + ctrlOne.text);
    print("controller two:   " + ctrlTwo.text);
    print("controller three: " + ctrlThree.text);
  }

  Widget buildFormElement(String label, int min, int max, int step, TextEditingController controller) {
    return Row(
      children: [
        Text(label),
        ElevatedButton(
          style: getStyleButtonStyle(),
          onPressed: () {
            onRemove(min, step, controller);
          },
          child: const Icon(Icons.remove),
        ),
        Text(controller.text),
        ElevatedButton(
          style: getStyleButtonStyle(),
          onPressed: () {
            onAdd(max, step, controller);
          },
          child: const Icon(Icons.remove),
        ),
      ],
    );
  }

  onRemove(int min, int step, TextEditingController controller) {
    int x = int.parse(controller.text);
    if (x > min) {
      setState(() {
        controller.text = (x - step).toString();
      });
    }
  }

  onAdd(int max, int step, TextEditingController controller) {
    int x = int.parse(controller.text);
    if (x < max) {
      setState(() {
        controller.text = (x + step).toString();
      });
    }
  }
}