【问题标题】:How do I get values out of a flutter List<class>?如何从颤动的 List<class> 中获取值?
【发布时间】:2022-09-25 18:44:57
【问题描述】:

我正在尝试在 Flutter 中使用 GetX 制作应用程序。 但是,在具有 Class 结构的 List 中使用 where 运算符对值进行排序后,我尝试将其保存为 List 并使用它。

在我当前的代码中,文本小部件中显示的字符串是\"\'Product\'的实例\". 我希望你们能告诉我如何在不运行 for 循环的情况下以简单的方式检索存储的值。

模型和列表数据如下。

class Product {
  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,
  });
}

List<Product> lodedProduct = [
  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\',
  ),
  Product(
    id: \'p3\',
    title: \'Yellow Scarf\',
    description: \'Warm and cozy - exactly what you need for the winter.\',
    price: 19.99,
    imageUrl: \'https://live.staticflickr.com/4043/4438260868_cc79b3369d_z.jpg\',
  ),
  Product(
    id: \'p4\',
    title: \'A Pan\',
    description: \'Prepare any meal you want.\',
    price: 49.99,
    imageUrl:
        \'https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Cast-Iron-Pan.jpg/1024px-Cast-Iron-Pan.jpg\',
  ),
];

要显示的部分如下。

import \'package:flutter/material.dart\';
import \'package:get/get.dart\';
import \'package:myshop/data/product_data.dart\';

import \'../models/product.dart\';

class ProductDetailScreen extends StatelessWidget {
  ProductDetailScreen({Key? key}) : super(key: key);

  var filteredList = lodedProduct
      .where((element) => element.id.contains(Get.arguments))
      .map((e) => e)
      .toList();
//Here, get the id from the previous page with Get.arguments. id is the 0th id in the List.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        centerTitle: true,
        title: Text(Get.arguments),
      ),
      body: Center(
        child: Container(
          child: Text(filteredList.toString()),
//Here, I want to get the value of filteredList as a string.
        ),
      ),
    );
  }
}

    标签: flutter dart flutter-getx


    【解决方案1】:

    尝试这个:

          body: Center(
            child: Column(
              children: filteredList.map((e){
                return Text(e.title);
              }).toList(),
            ),
          ),
    

    【讨论】:

    • 出现以下消息。参数类型“Iterable<Text>”不能分配给参数类型“List<Widget>”。
    • 嘿@JunK ...我已经进行了编辑-我添加了toList()
    • 是的。此代码有效。太感谢了。但是是否可以在 Text 小部件之外调用此代码?例如,Text(title) 只能这样调用。
    • 嗯,不是真的,因为您正在遍历列表。
    • 我找到了一种在 Text 小部件之外获取值的方法。
    【解决方案2】:
    final RxList<CustomModel> _list = <CustomModel>[].obs;
    
    int getLength() {
      return _list?.length ?? 0;
    }
    
    String getImage(int index) {
      return _list?.value[index].image ?? "Nil";
    }
    
    String getTitle(int index) {
      return _list?.value[index].title ?? "Nil";
    }
    

    【讨论】:

      【解决方案3】:

      最后我找到了答案。 正确的答案是使用 firstWhere,而不是 where。

       @override
        Widget build(BuildContext context) {
      
          final productId =
              controller.items.firstWhere((element) => element.id == Get.arguments);
      
          return Scaffold(
            appBar: AppBar(
              backgroundColor: Theme.of(context).primaryColor,
              centerTitle: true,
              title: Text(productId.title),
            ),
            body: Center(
              child: Column(
                children: [
                  Container(
                    width: double.maxFinite,
                    height: 250,
                    alignment: Alignment.bottomCenter,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        fit: BoxFit.cover,
                        image: NetworkImage(productId.imageUrl),
                      ),
                    ),
                    child: Container(
                      height: 50,
                      width: double.maxFinite,
                      alignment: Alignment.center,
                      color: Colors.black.withOpacity(0.3),
                      child: Text(
                        productId.title,
                        style: const TextStyle(
                          fontSize: 30,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 20),
                  Text(productId.description),
                  const SizedBox(height: 20),
                  Text('\$ ' + productId.price.toString()),
                ],
              ),
            ),
          );
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-24
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-10
        相关资源
        最近更新 更多