dart Flutter:铁路超高显示选项到从属下拉列表

sz81bmfz  于 2023-05-20  发布在  Flutter
关注(0)|答案(1)|浏览(75)

我是新的Flutter,我试图创建一个依赖的下拉列表。我有2个下拉字段,我的数据是类别产品。显示类别的第一个下拉列表正在工作。我的问题是在第二个下拉菜单上,没有显示基于所选类别值的选项。下面我将我的数据添加到一个特定的文件中。

localData.dart

import 'package:flutter/material.dart';

class LocalData with ChangeNotifier {
  static const List<Map<String, dynamic>> _categories = [
    {'id': 1, 'name': 'Electronics'},
    {'id': 2, 'name': 'Gaming'},
    {'id': 3, 'name': 'Accessories'},
  ];

  static List<Map<String, dynamic>> get categories {
    return [..._categories];
  }

  static List<Map<String, dynamic>> _products = [
    {
      'id': 1,
      'name': 'Smartphone',
      'categoriesId': [1]
    },
    {
      'id': 2,
      'name': 'Laptop',
      'categoriesId': [2, 3]
    },
    {
      'id': 3,
      'name': 'iPods',
      'categoriesId': [1, 3]
    },
  ];

  static List<Map<String, dynamic>> get products{
    return [..._products];
  }

基本上,在产品数据(_products)上,我有categoriesId,ID列表与类别ID(_categories)相合并。在我的代码中,我使用了**“where”**方法,但没有工作。我也使用了包含,但我有相同的结果。这是我的代码:

home.dart

class _HomePageState extends ConsumerState<HomePage> {
  int? category;
  int? product;

  List<Map<String, dynamic>> loadProd = [];

  @override
  Widget build(BuildContext context) {
    final themeService = ref.watch(themeServiceProvider);

    final ancScaffold = Scaffold.maybeOf(context);

    getProductsOptions() {
      loadProd = LocalData.products
          .where(
            (prod) => prod['categoriesId'] == category,
          )
          .toList();

      if (LocalData.products.isNotEmpty) {
        return loadProd.map((val) {
          return DropdownMenuItem(
              value: val['id'], child: Container(child: Text(val['name'])));
        }).toList();
      }
    }

    return Scaffold(
      appBar: AppBar(        
        bottom: themeService.appbarBottom(),
        elevation: 0,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Material(
              child: Container(
                child: Form(
                  child: Column(
                    children: [
                      SizedBox(
                        child: DropdownButtonFormField(
                          value: category,
                          isExpanded: true,
                          decoration: InputDecoration(
                            labelText: 'Categories',
                          ),
                          items: LocalData.categories.map((cat) {
                            return DropdownMenuItem(
                                value: cat['id'],
                                child: Container(child: Text(cat['name'])));
                          }).toList(),
                          onChanged: (value) {
                            setState(() {
                              if (value == null) {
                                return;
                              }
                              category = value as int;
                              //print(categories);
                            });
                          },
                        ),
                      ),
                      SizedBox(
                        child: DropdownButtonFormField(
                          value: product,
                          isExpanded: true,
                          decoration: InputDecoration(
                            labelText: 'Products',
                          ),
                          //value: categories,
                          items: getProductsOptions(),
                          onChanged: (prod) {
                            setState(() {
                              if (prod == null) {
                                return;
                              }
                              product = prod as int;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

有什么想法吗

rryofs0p

rryofs0p1#

可以使用此方法获取筛选项,

List<Map<String, dynamic>> getProductsByCategoryId(int id) {
    return _products.where((product) { // i would prefer model class+ try-catch
      return (product['categoriesId'] as List).contains(id);
    }).toList();
  }

下面是测试片段

class DDW extends StatefulWidget {
  const DDW({super.key});

  @override
  State<DDW> createState() => _DDWState();
}

class _DDWState extends State<DDW> {
  final _categories = [
    {'id': 1, 'name': 'Electronics'},
    {'id': 2, 'name': 'Gaming'},
    {'id': 3, 'name': 'Accessories'},
  ];

  final List<Map<String, dynamic>> _products = [
    {
      'id': 1,
      'name': 'Smartphone',
      'categoriesId': [1]
    },
    {
      'id': 2,
      'name': 'Laptop',
      'categoriesId': [2, 3]
    },
    {
      'id': 3,
      'name': 'iPods',
      'categoriesId': [1, 3]
    },
  ];

  List<Map<String, dynamic>> getProductsByCategoryId(int id) {
    return _products.where((product) {
      return (product['categoriesId'] as List).contains(id);
    }).toList();
  }

  int? category;
  int? product;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          DropdownButton(
            items: _categories
                .map((e) => DropdownMenuItem<int?>(
                      child: Text(e['name'] as String),
                      value: int.tryParse(e['id'].toString()),
                    ))
                .toList(),
            onChanged: (value) {
              category = value as int?;
              product = null;
              setState(() {});
            },
            value: category,
          ),
          DropdownButton<int?>(
            items: getProductsByCategoryId(category ?? 0)
                .map(
                  (e) => DropdownMenuItem<int?>(
                    value: int.tryParse(e['id'].toString()),
                    child: Text(e['name'].toString()),
                  ),
                )
                .toList(),
            onChanged: (value) {
              product = value;
              setState(() {});
            },
            value: product,
          ),
        ],
      ),
    );
  }
}

您可以检查另一个示例of multi-level dropdown

相关问题