GetX状态管理

时间:2020-08-06 15:56:34

标签: flutter state-management

我开始学习入门课程,在状态管理部分中,我决定学习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),
          )),
        ),
      ),
    );
  }
}

3 个答案:

答案 0 :(得分:3)

我刚刚解决了这个问题。 通过从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();
  }

答案 1 :(得分:0)

我不知道你真正想要做什么,如果它是我正在使用的带有 get 的数据库获取 模型'?.'属性像

实例:

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

我使用:

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

希望对你有帮助

答案 2 :(得分:0)

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

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

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

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