1

我开始学习 Flutter 课程,在状态管理部分我决定改为学习 GetX 状态管理。

无论如何,在这个商店教程中,我试图在按下时更改图标状态,但它没有。

文件product_item.dart

import 'package:flutter/material.dart';
import 'package:getx_pattern/app/ui/android/products_overview/widgets/product_details.dart';
import 'package:get/get.dart';

import '../../../theme/app_theme.dart';
import './product.dart';
import './products.dart';

class ProductItem extends StatelessWidget {
  final pIndex;
  // final String title;
  // final String imageUrl;

  ProductItem({
    this.pIndex,
  });

  productDetails() {
    Get.to(
      ProductDetailScreen(),
      arguments: product.findById(pIndex.id).title,
      transition: Transition.rightToLeft,
    );
  }

  final Products product = Get.put(Products());
  // final Product pp = Get.put(Product(
  //     id: null, title: null, description: null, price: null, imageUrl: null));

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(10.0),
      child: GetBuilder<Products>(
        builder: (_) => GridTile(
          child: GestureDetector(
            onTap: () => productDetails(),
            child: Image.network(
              product.findById(pIndex.id).imageUrl,
              fit: BoxFit.cover,
            ),
          ),
          footer: GridTileBar(
            backgroundColor: Colors.black87,
            leading: IconButton(
                icon: Icon(product.findById(pIndex.id).isFavorite
                    ? Icons.favorite
                    : Icons.favorite_border),
                color: appThemeData.accentColor,
                onPressed: () {
                  product.findById(pIndex.id).toggleFavoriteStatus();
                  // print(_.items[pIndex].isFavorite);
                }),
            trailing: IconButton(
                icon: Icon(Icons.shopping_cart),
                color: appThemeData.accentColor,
                onPressed: () {}),
            title: Text(
              product.findById(pIndex.id).title,
              textAlign: TextAlign.center,
            ),
          )),
      ));
  }
}

文件product.dart

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

class Product extends GetxController {
  final String id;
  final String title;
  final String description;
  final double price;
  final String imageUrl;
  bool isFavorite;

  Product({
    @required this.id,
    @required this.title,
    @required this.description,
    @required this.price,
    @required this.imageUrl,
    this.isFavorite = false,
  });

  void toggleFavoriteStatus() {
    isFavorite = !isFavorite;
    update();
  }
}

文件products.dart

import 'package:get/get.dart';

import 'product.dart';

class Products extends GetxController {
  List<Product> items = [];

  Products();

  @override
  onInit() {
    items = [
      Product(
        id: 'p1',
        title: 'Red Shirt',
        description: 'A red shirt - it is pretty red!',
        price: 29.99,
        imageUrl:
            'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
      ),
      Product(
        id: 'p2',
        title: 'Trousers',
        description: 'A nice pair of trousers.',
        price: 59.99,
        imageUrl:
            'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Trousers%2C_dress_%28AM_1960.022-8%29.jpg/512px-Trousers%2C_dress_%28AM_1960.022-8%29.jpg',
      ),
    ];
    update();
    super.onInit();
  }

  List get myitems => [...items];

  Product findById(String id) {
    return items.firstWhere((prod) => prod.id == id);
  }

  void addProduct() {
    //_items.add(value);
    update();
  }
}

文件products_grid

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

import './product.dart';
import './product_item.dart';
import './products.dart';

class ProductsGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetBuilder<Products>(
      init: Products(),
      builder: (data) => GridView.builder(
          padding: const EdgeInsets.all(10.0),
          itemCount: data.items.length,
          itemBuilder: (ctx, index) => ProductItem(
                pIndex: data.items[index],
              ),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 3 / 2,
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
          )),
    );
  }
}

文件product_details

import 'package:getx_pattern/app/ui/android/products_overview/widgets/products.dart';

import '../../../theme/app_theme.dart';

class ProductDetailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: appThemeData,
      home: SafeArea(
        child: Scaffold(
          appBar: AppBar(
              title: GetBuilder<Products>(
            init: Products(),
            builder: (data) => Text(Get.arguments),
          )),
        ),
      ),
    );
  }
}
4

3 回答 3

9

我刚刚通过从文件product.dart移动方法解决了这个问题,

void toggleFavoriteStatus() {
    isFavorite = !isFavorite;
    update();
}

归档products.dart

void toggleFavoriteStatus(String id) {
    items.firstWhere((prod) => prod.id == id).isFavorite =
        !items.firstWhere((prod) => prod.id == id).isFavorite;
    update();
}
于 2020-08-06T17:24:44.673 回答
0

这是因为您正在更新product控制器,但productsGetBuilder. 我的意思是您GetBuilder必须使用已更新的相同控制器,但您使用的是GetBuilder<Products>(...(而不是GetBuilder<Product>(...)。

所以有两种可能的方法来解决这个问题:

第一:正如MNMB所说,是更新Products控制器。

第二:在小部件中更改GetBuilder<Products>(...为。GetBuilder<Product>(...ProductItem

于 2021-03-09T15:55:56.957 回答
0

我不知道你真正想做什么。如果它是使用get获取的数据库,我正在使用模型'?。' 属性喜欢而不是:

Image.network(
    product.findById(pIndex.id).imageUrl,
    fit: BoxFit.cover,
 ),...

我用:

Image.network(
    product?.imageUrl,
    fit: BoxFit.cover,
),...

于 2021-01-23T12:16:04.210 回答