简体   繁体   English

Flutter/Dart - 文本值未正确显示

[英]Flutter/Dart - Text value not showing correctly

I am trying to create a shopping cart using provider and display the number of items currently in the cart on my homepage.我正在尝试使用提供程序创建一个购物车,并在我的主页上显示当前购物车中的商品数量。 When I create my cart icon with a text widget overlaid, the value being shown does not reflect the number of items in the cart.当我创建带有文本小部件的购物车图标时,显示的值不反映购物车中的项目数量。

Here is my code:这是我的代码:

 class OurShoppingBasketIcon extends StatelessWidget {
  const OurShoppingBasketIcon({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.center,
      child: InkWell(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => ShoppingBasketScreen()),
          );
        },
        child: Stack(
          children: <Widget>[
            new Icon(
              Icons.shopping_cart_outlined,
              color: Colors.white,
            ),
            new Positioned(
              right: 0,
              child: new Container(
                padding: EdgeInsets.all(1),
                decoration: new BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(6),
                ),
                constraints: BoxConstraints(
                  minWidth: 12,
                  minHeight: 12,
                ),
                child: Text(
                  context.read<ShoppingBasket>().items.length.toString(),
                  style: new TextStyle(
                    color: Colors.white,
                    fontSize: 8,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

This is where the icon is implemented:这是实现图标的地方:

  class OurHomePage extends StatefulWidget {
  @override
  _OurHomePageState createState() => _OurHomePageState();
}

class _OurHomePageState extends State<OurHomePage> {

  @override
  Widget build(BuildContext context) {
    return Consumer<OurUser>(
      builder: (_, user, __) {
        return ChangeNotifierProvider<SignInViewModel>(
          create: (_) => SignInViewModel(context.read),
          builder: (_, child) {
            return Scaffold(
              appBar: AppBar(
                title: Text("My app"),
                actions: [
                  OurShoppingBasketIcon(),
                  IconButton(
                    icon: Icon(
                      Icons.logout,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      context.read<FirebaseAuthService>().signOut();
                    },
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }
}

There are 2 items in the cart as of writing this:撰写本文时,购物车中有 2 件商品:

在此处输入图像描述

But the icon on the homepage does not change:但是首页的图标没有变化:

在此处输入图像描述

Here is my main.dart:这是我的main.dart:

  void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(
    MultiProvider(
      providers: [
        Provider(
          create: (_) => FirebaseAuthService(),
        ),
        StreamProvider<OurUser>(
            create: (context) =>
                context.read<FirebaseAuthService>().onAuthStateChanged),
        ChangeNotifierProvider.value(
          value: ShoppingBasket(),
        ),
      ],
      child: MaterialApp(theme: OurTheme().buildTheme(), home: OurHomePage()),
    ),
  );
}

perhaps if you watch for the value it will be updated dynamically:也许如果您注意该值,它将动态更新:

 context.watch<ShoppingBasket>().items.length.toString(), //<-- watch instead of read

The OurHomePage needs to be wrapped in the Provider<ShoppingBasket> . OurHomePage需要包装在Provider<ShoppingBasket>中。

return Provider<ShoppingBasket>(
      create: (context) => ShoppingBasket(),
      child: Consumer<OurUser>(
      builder: (_, user, __) {
        return ChangeNotifierProvider<SignInViewModel>(
          create: (_) => SignInViewModel(context.read),
          builder: (_, child) {
            return Scaffold(
              appBar: AppBar(
                title: Text("My app"),
                actions: [
                  OurShoppingBasketIcon(),
                  IconButton(
                    icon: Icon(
                      Icons.logout,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      context.read<FirebaseAuthService>().signOut();
                    },
                  ),
                ],
              ),
              ),
            );
          },
        );

I forgot to NotifyListeners() in my Change Notifier class:我忘记在我的更改通知器 class 中使用 NotifyListeners():

  class ShoppingBasket extends ChangeNotifier {
  Map<String, SingleBasketItem> _items = {};

  Map<String, SingleBasketItem> get items {
    return {..._items};
  }

  void addItem(String id) {
    _items.putIfAbsent(
      id,
      () => SingleBasketItem(id),
    );
    notifyListeners(); //HERE
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM