从另一个类扑来中从另一个班级中获取整数的价值

发布于 2025-01-28 17:21:27 字数 1587 浏览 4 评论 0原文

学习Flutter,我正在建造一个我想用于购物车的柜台。我有一个问题,可以检索我创建的计数器状态小部件的整数值,我希望文本以计数器的值来更新自己。

这是计数器的代码

import 'package:flutter/material.dart';

class TheCounter extends StatefulWidget {
  int counter = 0;
  int get counterValue => counter;

  @override
  _TheCounterState createState() => _TheCounterState();
}

class _TheCounterState extends State<TheCounter> {
  void increaseCounter() {
    setState(() {
      if (widget.counter >= 0) {
        widget.counter++;
      }
    });
  }

  void decreaseCounter() {
    setState(() {
      if (widget.counter > 0) {
        widget.counter--;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        IconButton(icon: Icon(Icons.add), onPressed: increaseCounter),
        Text('${widget.counter}'),
        IconButton(icon: Icon(Icons.remove), onPressed: decreaseCounter)
      ],
    );
  }
}

,以下是主文件

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

void main() {
  runApp(Count());
}

class Count extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    int counting = TheCounter().counterValue;
    return MaterialApp(
      title: 'Counter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Counter Test'),
        ),
        body: Column(
          children: [
            TheCounter(),
            Text('$counting'),
            TheCounter(),
            TheCounter(),
          ],
        ),
      ),
    );
  }
}

。我该怎么做才能实现?

Learning Flutter and I am building a counter that I would like to use for a cart. I have a problem retrieving the integer value of the counter stateful widget I created and i'd like a Text to update itself with the value of the Counter.

Here is the Code for the Counter

import 'package:flutter/material.dart';

class TheCounter extends StatefulWidget {
  int counter = 0;
  int get counterValue => counter;

  @override
  _TheCounterState createState() => _TheCounterState();
}

class _TheCounterState extends State<TheCounter> {
  void increaseCounter() {
    setState(() {
      if (widget.counter >= 0) {
        widget.counter++;
      }
    });
  }

  void decreaseCounter() {
    setState(() {
      if (widget.counter > 0) {
        widget.counter--;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        IconButton(icon: Icon(Icons.add), onPressed: increaseCounter),
        Text('${widget.counter}'),
        IconButton(icon: Icon(Icons.remove), onPressed: decreaseCounter)
      ],
    );
  }
}

And here is the main.dart file

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

void main() {
  runApp(Count());
}

class Count extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    int counting = TheCounter().counterValue;
    return MaterialApp(
      title: 'Counter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Counter Test'),
        ),
        body: Column(
          children: [
            TheCounter(),
            Text('$counting'),
            TheCounter(),
            TheCounter(),
          ],
        ),
      ),
    );
  }
}

I'd like the Text to update itself with the value of the counter whenever the add or remove button is clicked. What do I do to achieve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

银河中√捞星星 2025-02-04 17:21:27

首先,我们需要决定更新会发生。在这种情况下,count小部件文本需要更新。
因此,需要将其转换为statefulwidget

接下来是我们如何从thecounter窗口小部件检索计数器。您可以使用回调方法或状态管理软件包,例如提供商,RiverPod,Bloc等。您可以检查 doc

在这里,我使用的函数将在count上获取 count value on thecounter widget时。


void main() {
  runApp(MaterialApp(title: 'Counter', home: Count()));
}

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

  @override
  State<Count> createState() => _CountState();
}

class _CountState extends State<Count> {
  int initNumberOfCounter = 4;

  late List<int> countersValue = List.generate(initNumberOfCounter, (index) => 0);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Counter Test'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            countersValue.add(0);
          });
        },
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: countersValue.length,
              itemBuilder: (context, index) {
                return Row(
                  // mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    TheCounter(
                      initCountValue: countersValue[index],
                      countValueCallback: (v) {
                        setState(() {
                          countersValue[index] = v;
                        });
                      },
                    ),
                    const SizedBox(
                      width: 40,
                    ),
                    Text("${countersValue[index]}"),
                  ],
                );
              },
            ),
          )
        ],
      ),
    );
  }
}

class TheCounter extends StatefulWidget {
  final Function(int) countValueCallback;
  final int initCountValue;
  const TheCounter({
    Key? key,
    required this.countValueCallback,
    this.initCountValue = 0,
  }) : super(key: key);

  @override
  _TheCounterState createState() => _TheCounterState();
}

class _TheCounterState extends State<TheCounter> {
  ///this use within the current state
  late int counter;

  @override
  void initState() {
    super.initState();

    ///set counter value for the 1st time
    counter = widget.initCountValue;
  }

  void increaseCounter() {
    setState(() {
      if (counter >= 0) {
        counter++;
      }
    });

    /// back to parent widget
    widget.countValueCallback(counter);
  }

  void decreaseCounter() {
    setState(() {
      if (counter > 0) {
        counter--;
      }
    });
    widget.countValueCallback(counter);
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        IconButton(icon: Icon(Icons.add), onPressed: increaseCounter),
        Text('${counter}'),
        IconButton(icon: Icon(Icons.remove), onPressed: decreaseCounter)
      ],
    );
  }
}

Firstly, we need to make a decision where the update will happen. In this case the Count widget text need to update.
Therefore, need to convert this as StatefulWidget.

Next thing is how we can retrieve counter from TheCounter widget. You can use callback method, or state management package like provider, riverpod, bloc etc. You can check the doc

Here I am using a function that will get update value on Count whenever the count value change on TheCounter widget.


void main() {
  runApp(MaterialApp(title: 'Counter', home: Count()));
}

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

  @override
  State<Count> createState() => _CountState();
}

class _CountState extends State<Count> {
  int initNumberOfCounter = 4;

  late List<int> countersValue = List.generate(initNumberOfCounter, (index) => 0);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Counter Test'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            countersValue.add(0);
          });
        },
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: countersValue.length,
              itemBuilder: (context, index) {
                return Row(
                  // mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    TheCounter(
                      initCountValue: countersValue[index],
                      countValueCallback: (v) {
                        setState(() {
                          countersValue[index] = v;
                        });
                      },
                    ),
                    const SizedBox(
                      width: 40,
                    ),
                    Text("${countersValue[index]}"),
                  ],
                );
              },
            ),
          )
        ],
      ),
    );
  }
}

class TheCounter extends StatefulWidget {
  final Function(int) countValueCallback;
  final int initCountValue;
  const TheCounter({
    Key? key,
    required this.countValueCallback,
    this.initCountValue = 0,
  }) : super(key: key);

  @override
  _TheCounterState createState() => _TheCounterState();
}

class _TheCounterState extends State<TheCounter> {
  ///this use within the current state
  late int counter;

  @override
  void initState() {
    super.initState();

    ///set counter value for the 1st time
    counter = widget.initCountValue;
  }

  void increaseCounter() {
    setState(() {
      if (counter >= 0) {
        counter++;
      }
    });

    /// back to parent widget
    widget.countValueCallback(counter);
  }

  void decreaseCounter() {
    setState(() {
      if (counter > 0) {
        counter--;
      }
    });
    widget.countValueCallback(counter);
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        IconButton(icon: Icon(Icons.add), onPressed: increaseCounter),
        Text('${counter}'),
        IconButton(icon: Icon(Icons.remove), onPressed: decreaseCounter)
      ],
    );
  }
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文