簡體   English   中英

從flutter中的另一個類的有狀態小部件中獲取整數的值

[英]Get the value of an integer from a stateful widget from another class in flutter

學習 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)
      ],
    );
  }
}

這是 main.dart 文件

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(),
          ],
        ),
      ),
    );
  }
}

每當單擊添加或刪除按鈕時,我希望文本使用計數器的值更新自身。 我該怎么做才能做到這一點?

首先,我們需要決定更新將在哪里進行。 在這種情況下, Count小部件文本需要更新。 因此,需要將其轉換為StatefulWidget

接下來是我們如何從TheCounter小部件中檢索計數器。 您可以使用回調方法或狀態管理包,如 provider、riverpod、bloc 等。您可以查看文檔

在這里,我使用了一個函數,只要TheCounter小部件上的計數值發生變化,就會在Count上獲取更新值。


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)
      ],
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM