GetX 状态管理

GetX state management

我开始学习 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),
          )),
        ),
      ),
    );
  }
}

我刚刚通过从文件 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();
}

我不知道你到底想做什么。如果是使用 get 获取数据库,我正在使用模型'?.'属性类似于:

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

我使用:

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

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

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

首先:正如MNMB所说,是更新Products控制器。

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