如何重建Singleton Value Change的颤音小部件

发布于 2025-02-14 01:26:09 字数 2353 浏览 0 评论 0原文

每当我的全球Singelton中的价值变化时,我都在尝试重建一个陈述的小部件,但我很困惑。

我的目标是每次在整个应用程序中更改推车时重建我的购物车图标。

我知道,只要更改Singelton 值,我就需要发出通知。并在我的状态小部件中聆听该通知,但是我该怎么做?

任何帮助将不胜感激。

我的全球Singelton

library #######.globals;

import 'package:flutter/material.dart';

class GlobalSingleton extends ChangeNotifier {
  static final GlobalSingleton _instance = GlobalSingleton._internal();

  // passes the instantiation to the _instance object
  factory GlobalSingleton() {
    return _instance;
  }

  //initialize variables in here
  GlobalSingleton._internal() {
    cartSize = 0;
  }

  late int cartSize;
}

我的状态小部件

import 'package:######/globals/globals.dart';
import 'package:flutter/material.dart';

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

  @override
  State<BuildMarketplaceCartIcon> createState() =>
      _BuildMarketplaceCartIconState();
}

class _BuildMarketplaceCartIconState extends State<BuildMarketplaceCartIcon> {
  CRUDMarketplaceCart localCartData = CRUDMarketplaceCart();

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
      },
      child: Container(
        width: 72,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const <Widget>[
                Icon(Icons.shopping_cart),
                Text(
                  'Cart',
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
            Positioned(
              top: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 6,
                  vertical: 2,
                ),
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                ),
                alignment: Alignment.center,
                child: Text(
                  '${globals.GlobalSingleton().cartSize}',
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

I am trying to rebuild a stateful widget every time a value in my global Singelton is changed but I'm stumped.

My goal is to rebuild my Cart Icon every time the cartSize is changed throughout my app.

I know I need to send out a notification whenever the Singelton cartSize value is changed. and listen for that notification in my stateful widget but how do I do this?

Any help is greatly appreciated.

My Global Singelton

library #######.globals;

import 'package:flutter/material.dart';

class GlobalSingleton extends ChangeNotifier {
  static final GlobalSingleton _instance = GlobalSingleton._internal();

  // passes the instantiation to the _instance object
  factory GlobalSingleton() {
    return _instance;
  }

  //initialize variables in here
  GlobalSingleton._internal() {
    cartSize = 0;
  }

  late int cartSize;
}

My stateful Widget

import 'package:######/globals/globals.dart';
import 'package:flutter/material.dart';

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

  @override
  State<BuildMarketplaceCartIcon> createState() =>
      _BuildMarketplaceCartIconState();
}

class _BuildMarketplaceCartIconState extends State<BuildMarketplaceCartIcon> {
  CRUDMarketplaceCart localCartData = CRUDMarketplaceCart();

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
      },
      child: Container(
        width: 72,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const <Widget>[
                Icon(Icons.shopping_cart),
                Text(
                  'Cart',
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
            Positioned(
              top: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 6,
                  vertical: 2,
                ),
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                ),
                alignment: Alignment.center,
                child: Text(
                  '${globals.GlobalSingleton().cartSize}',
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

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

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

发布评论

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

评论(1

娇纵 2025-02-21 01:26:09

使用changeNotifier时,您需要调用notifyListeners当值更改时。您还需要让小部件收听changeNotifier,以便知道何时重建。

这样做的最常见方法是使用提供者 package,其中包括conseNotifierProviderProviderProviderProviderProviderProvider小部件。

使用提供商,您的代码看起来像这样:

class GlobalSingleton extends ChangeNotifier {
  static final GlobalSingleton _instance = GlobalSingleton._internal();

  // passes the instantiation to the _instance object
  factory GlobalSingleton() {
    return _instance;
  }

  //initialize variables in here
  GlobalSingleton._internal() {
    _cartSize = 0;
  }

  late int _cartSize;

  int get cartSize => _cartSize;

  void set cartSize(int newCartSize) {
    _cartSize = newCartSize;
    notifyListeners();
  }
}

在这里,我们更新您的Singleton,以便每当设置CartSize时,都会调用notifyListeners()

接下来,您需要更新小部件以收听更改:

import 'package:######/globals/globals.dart';
import 'package:flutter/material.dart';

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

  @override
  State<BuildMarketplaceCartIcon> createState() =>
      _BuildMarketplaceCartIconState();
}

class _BuildMarketplaceCartIconState extends State<BuildMarketplaceCartIcon> {
  CRUDMarketplaceCart localCartData = CRUDMarketplaceCart();

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {},
      child: Container(
        width: 72,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const <Widget>[
                Icon(Icons.shopping_cart),
                Text(
                  'Cart',
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
            Positioned(
              top: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 6,
                  vertical: 2,
                ),
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                ),
                alignment: Alignment.center,
                child: ChangeNotifierProvider.value(
                  value: GlobalSingleton(),
                  child: Consumer<GlobalSingleton>(
                    builder: (context, singleton, child) {
                      return Text(
                        '${singleton.cartSize}',
                      );
                    },
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

在这里,我将提供商窗口小部件直接封闭consumer widget-但是,如果您需要Singleton的值在一个以上的位置,您可以将提供商更高的位置放在小部件树上,以便它是任何consumper的共同祖先,它会听取Singleton中的更改。

When using ChangeNotifier you need to call notifyListeners when the value changes. You also need to have your widget listen to the ChangeNotifier, so that it knows when to rebuild.

The most common way to go about that is to use the provider package, which includes the ChangeNotifierProvider widget.

Using provider, your code would look something like this:

class GlobalSingleton extends ChangeNotifier {
  static final GlobalSingleton _instance = GlobalSingleton._internal();

  // passes the instantiation to the _instance object
  factory GlobalSingleton() {
    return _instance;
  }

  //initialize variables in here
  GlobalSingleton._internal() {
    _cartSize = 0;
  }

  late int _cartSize;

  int get cartSize => _cartSize;

  void set cartSize(int newCartSize) {
    _cartSize = newCartSize;
    notifyListeners();
  }
}

Here, we update your singleton so that it will call notifyListeners() whenever the cartSize is set.

Next you'll need to update your widget to listen to the changes:

import 'package:######/globals/globals.dart';
import 'package:flutter/material.dart';

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

  @override
  State<BuildMarketplaceCartIcon> createState() =>
      _BuildMarketplaceCartIconState();
}

class _BuildMarketplaceCartIconState extends State<BuildMarketplaceCartIcon> {
  CRUDMarketplaceCart localCartData = CRUDMarketplaceCart();

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {},
      child: Container(
        width: 72,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const <Widget>[
                Icon(Icons.shopping_cart),
                Text(
                  'Cart',
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
            Positioned(
              top: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 6,
                  vertical: 2,
                ),
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                ),
                alignment: Alignment.center,
                child: ChangeNotifierProvider.value(
                  value: GlobalSingleton(),
                  child: Consumer<GlobalSingleton>(
                    builder: (context, singleton, child) {
                      return Text(
                        '${singleton.cartSize}',
                      );
                    },
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Here I put the Provider widget as directly enclosing the Consumer widget - however, if you need the singleton's value in more than one place, you can put the Provider higher up the widget tree so that it's a common ancestor of any Consumer that listens to changes in the singleton.

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