【问题标题】:How to count and get a list of specified value in dart and flutter如何在飞镖和颤振中计数并获取指定值的列表
【发布时间】:2020-12-31 14:36:54
【问题描述】:

我有以下 UML 类图: UML class diagram

我想显示在每个公司中找到的所有特色产品的列表视图。 我希望只获得特色产品

  • 产品 00(来自 abc 公司)
  • 产品 02(来自 abc 公司)
  • 产品 11(来自 xyz 公司)

但下面的代码只给了我第一项 product 00

我试着统计特色产品 但长度始终为 1。

List<Product> temps;
    for (var i = 0; i < companies.length; i++) {
      
      temps = companies[i]
          .products
          .where((fp) => fp.isFeatured == true)
          .toList();
    }
    print('===> ${temps.length}'); // <----- here

这是带有数据的模型 Dart 代码:

class Product {
  final int id;
  final String name;
  final double price;
  final bool isFeatured;

  Product({
    this.id,
    this.name,
    this.price,
    this.isFeatured,
  });
}

class Company {
  final int id;
  final String name;
  final List<Product> products;

  Company({
    this.id,
    this.name,
    this.products,
  });
}

List<Product> productsOfCompanyAbc = [
  Product(
    id: 0,
    name: 'product 00',
    price: 10.0,
    isFeatured: true,
  ),
  Product(
    id: 1,
    name: 'product 01',
    price: 20.0,
    isFeatured: false,
  ),
  Product(
    id: 2,
    name: 'product 02',
    price: 25.0,
    isFeatured: true,
  ),
];

List<Product> productsOfCompanyXyz = [
  Product(
    id: 0,
    name: 'product 11',
    price: 30.0,
    isFeatured: true,
  ),
  Product(
    id: 1,
    name: 'product 12',
    price: 40.0,
    isFeatured: false,
  ),
];

List<Company> companies = [
  Company(
    id: 0,
    name: 'Company abc',
    products: productsOfCompanyAbc,
  ),
  Company(
    id: 1,
    name: 'Company xyz',
    products: productsOfCompanyXyz,
  )
];

这是 Flutter 示例:

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  int countFeaturedProducts() {
    List<Product> temps;
    for (var i = 0; i < companies.length; i++) {
      
      temps = companies[i]
          .products
          .where((fp) => fp.isFeatured == true)
          .toList();
      // this product TRUE items that is featured
      for (var item in temps) {
        print(item.name);
       
      }
    }
    print('===> ${temps.length}');
    print('===> out');
    return temps.length;
  }


List<Product> featuredProducts(int index){
    List<Product> allFeatured;
    for (var i = 0; i < companies[index].products.length; i++) {
      allFeatured = companies[index].products;
    }
    return allFeatured;
  }
    
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: 100,
        color: Colors.blueGrey,
        child: ListView.builder(
          itemCount: countFeaturedProducts(), //<------- Here give length 1.
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(featuredProducts(index)[index].name), //<------- Here give only one Product 00.
            );
          },
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:
    temps = companies[i]
              .products
              .where((fp) => fp.isFeatured == true)
              .toList();
    

    在每个循环中替换 temps。听起来您想将特色项目附加到聚合列表中。所以你想要这样的东西:

    temps.addAll(companies[i]
              .products
              .where((fp) => fp.isFeatured == true)
              .toList());
    

    但是直接使用它会失败,因为temps 没有初始化,所以你需要用这样的东西来初始化它:

    List<Product> temps = [];
        for (var i = 0; i < companies.length; i++) {
          
          temps.addAll(companies[i]
              .products
              .where((fp) => fp.isFeatured == true));
        }
        print('===> ${temps.length}'); // <----- here
    

    但是,除了循环,更简单的方法是使用 expand 函数:

    List<Product> temps = companies.expand((company) => company.products.where((product) => product.isFeatured)).toList();
    print('===> ${temps.length}'); // <----- here
    

    【讨论】:

    • 它给出以下错误:NoSuchMethodError: invalid member on null: 'addAll'
    • @fromearth 我更新了我的答案以及一种可能更容易的新方法。如果这解决了您的问题,请接受它。
    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 2020-08-12
    • 2021-01-24
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多