Как добавить еще один список элементов для DropDownMenu, а затем использовать элементы в виджете - PullRequest
2 голосов
/ 10 июля 2020

Итак, я пытаюсь сделать выпадающее меню для каждой опции и вставить для каждой другой список элементов. Прежде всего, поскольку мой виджет Dropdownmenu имеет одинаковые свойства для одного и другого, я извлек этот виджет в другой класс с именем «MenuDropDown». Вот код виджета.

import 'package:flutter/material.dart';
import 'List.dart';

class MenuDropDown extends StatefulWidget {
  final String dropdownText;
  final List<DropdownMenuItem<String>> itemList;
  MenuDropDown({this.dropdownText, this.itemList});
  @override
  _MenuDropDownState createState() => _MenuDropDownState();
}

class _MenuDropDownState extends State<MenuDropDown> {
  String selectedItem;

  List<DropdownMenuItem> getGroomingTypeList() {
    List<DropdownMenuItem<String>> dropdownItems = [];
    for (String groomingType in groomingTypeList) {
      var newItem = DropdownMenuItem(
        child: Text(groomingType),
        value: groomingType,
      );
      dropdownItems.add(newItem);
    }
    return dropdownItems;
  }

  List<DropdownMenuItem> getCatBreedsList() {
    List<DropdownMenuItem<String>> dropdownItems = [];
    for (String catBreed in catBreedsList) {
      var newItem = DropdownMenuItem(
        child: Text(catBreed),
        value: catBreed,
      );
      dropdownItems.add(newItem);
    }
    return dropdownItems;
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 8.0, 0, 10.0),
      child: Container(
        width: 325.0,
        height: 50.0,
        decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.black45,
              offset: Offset(2.5, 5.5),
              blurRadius: 5.0,
            )
          ],
          borderRadius: BorderRadius.circular(8),
          color: Colors.white,
        ),
        child: DropdownButtonHideUnderline(
          child: DropdownButton(
              value: selectedItem,
              hint: Padding(
                padding: const EdgeInsets.fromLTRB(22.0, 0, 0, 0),
                child: Text(
                  widget.dropdownText,
                  style: TextStyle(),
                ),
              ),
              items: widget.itemList,
              onChanged: (value) {
                setState(() {
                  selectedItem = value;
                });
              }),
        ),
      ),
    );
  }
}

выше здесь Я создал метод для получения элемента списка из класса списка, который я уже создал. Сначала он работает, если я жестко запрограммировал в свойства элементов Dropdownmenu, чтобы отобразить список элементов, но поскольку мне нужно использовать другой список для другого виджета, я думаю, что если я попытаюсь создать переменную List с именем itemList, чтобы я мог получить к ней доступ из другого класса где я могу вызвать только настраиваемую переменную.

И это виджет с отслеживанием состояния, в котором я использую свой виджет извлеченного раскрывающегося меню:

import 'package:flutter/material.dart';
import 'TitleName.dart';
import 'dropdownmenu.dart';

class InformationDetail extends StatefulWidget {
  @override
  _InformationDetailState createState() => _InformationDetailState();
}

class _InformationDetailState extends State<InformationDetail> {
  MenuDropDown _menuDropDown = MenuDropDown();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          child: Column(
            children: <Widget>[
              Container(
                margin: EdgeInsets.fromLTRB(25.0, 68.0, 70.0, 26.0),
                child: Text(
                  'Information Detail',
                  style: TextStyle(fontSize: 35.0),
                ),
              ),
              Column(
                // Wrap Column
                children: <Widget>[
                  Column(
                    children: <Widget>[
                      TitleName(
                        titleText: 'Grooming Type',
                        infoIcon: Icons.info,
                      ),
                      MenuDropDown(
                        dropdownText: 'Grooming Type...',
                      //I'm trying to implement the list here with a custom variable that contain 
                        a method with different list in dropdownmenu class
                      itemlist: getGroomingTypeList(),
                      ),
                      TitleName(
                        titleText: 'Cat Breeds',
                      ),
                      MenuDropDown(
                        dropdownText: 'Cat Breeds...',
                      ),
                      TitleName(
                        titleText: 'Cat Size',
                        infoIcon: Icons.info,
                      ),
                      MenuDropDown(
                        dropdownText: 'Cat Size...',
                      ),
                      TitleName(
                        titleText: 'Add-On Services',
                      ),
                      MenuDropDown(
                        dropdownText: 'Add - On Services...',
                      ),
                      Container(
                        margin: EdgeInsets.fromLTRB(0, 15.0, 0, 0),
                        width: 75.0,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          shape: BoxShape.rectangle,
                          border: Border.all(
                            color: Colors.black,
                          ),
                          borderRadius: BorderRadius.circular(12.0),
                        ),
                        child: IconButton(
                          icon: Icon(Icons.arrow_forward),
                          onPressed: () {
                            Navigator.of(context)
                                .pushNamed('/ReservationDetail');
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

И это список, который я хочу использовать для каждого виджета выпадающего меню

const List groomingTypeList = ['Basic Grooming', 'Full Grooming'];

const List catBreedsList = [
  'Persia',
  'Anggora',
  'Domestic',
  'Maine Coon',
  'Russian Blue',
  'Slamese',
  'Munchkin',
  'Ragdoll',
  'Scottish Fold',
];

const List catSizeList = [
  'Small Size',
  'Medium Size',
  'Large Size',
  'Extra Large Size',
];

const List addOnServicesList = [
  'Spa & Massage',
  'Shaving Hair / Styling',
  'Injection Vitamis Skin & Coat',
  'Cleaning Pet House and Environment',
  'Fur Tangled Treatment',
];

Я застрял оттуда. Как использовать другой список для каждого созданного мной виджета раскрывающегося меню, потому что я уже пытался создать конструктор, переменную и метод, чтобы использовать их отдельно, но вместо этого я получил сообщение об ошибке:

тип «Список» не является подтипом типа «Список »

Думаю, я изначально неправильно реализовал его. Мне действительно нужна помощь в другом решении этих проблем. спасибо всем!

1 Ответ

1 голос
/ 10 июля 2020

Просто проверьте код, в который я внес некоторые изменения:

import 'package:flutter/material.dart';

void main() => runApp(InformationDetail());

class InformationDetail extends StatefulWidget {
  @override
  _InformationDetailState createState() => _InformationDetailState();
}

class _InformationDetailState extends State<InformationDetail> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Container(
            child: Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.fromLTRB(25.0, 68.0, 70.0, 26.0),
                  child: Text(
                    'Information Detail',
                    style: TextStyle(fontSize: 35.0),
                  ),
                ),
                Column(
                  // Wrap Column
                  children: <Widget>[
                    Column(
                      children: <Widget>[
                        Text(
                          'Grooming Type',
                        ),
                        MenuDropDown(
                          dropdownText: 'Grooming Type...',
                          //I'm trying to implement the list here with a custom variable that contain
                          // a method with different list in dropdownmenu class
                          type: "groomingType",
                        ),
                        Text(
                          'Cat Breeds',
                        ),
                        MenuDropDown(
                          dropdownText: 'Cat Breeds...',
                          type: "catBreeds",
                        ),
                        Text(
                          'Cat Size',
                        ),
                        MenuDropDown(
                          dropdownText: 'Cat Size...',
                          type: "catSize",
                        ),
                        Text(
                          'Add-On Services',
                        ),
                        MenuDropDown(
                          dropdownText: 'Add - On Services...',
                          type: "addOnServices",
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(0, 15.0, 0, 0),
                          width: 75.0,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.rectangle,
                            border: Border.all(
                              color: Colors.black,
                            ),
                            borderRadius: BorderRadius.circular(12.0),
                          ),
                          child: IconButton(
                            icon: Icon(Icons.arrow_forward),
                            onPressed: () {
                              Navigator.of(context)
                                  .pushNamed('/ReservationDetail');
                            },
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class MenuDropDown extends StatefulWidget {
  final String dropdownText;
  final String type;
  MenuDropDown({this.dropdownText, this.type});
  @override
  _MenuDropDownState createState() => _MenuDropDownState();
}

class _MenuDropDownState extends State<MenuDropDown> {
  String selectedItem;
  List<String> dropdownItems = [];

  List<String> groomingTypeList = ['Basic Grooming', 'Full Grooming'];

  List<String> catBreedsList = [
    'Persia',
    'Anggora',
    'Domestic',
    'Maine Coon',
    'Russian Blue',
    'Slamese',
    'Munchkin',
    'Ragdoll',
    'Scottish Fold',
  ];

  List<String> catSizeList = [
    'Small Size',
    'Medium Size',
    'Large Size',
    'Extra Large Size',
  ];

  List<String> addOnServicesList = [
    'Spa & Massage',
    'Shaving Hair / Styling',
    'Injection Vitamis Skin & Coat',
    'Cleaning Pet House and Environment',
    'Fur Tangled Treatment',
  ];

  List<String> getListBasedOnName(String value) {
    print(value);
    switch (value) {
      case "groomingType":
        return groomingTypeList;

        break;
      case "catBreeds":
        return catBreedsList;
        break;

      case "catSize":
        return catSizeList;
        break;
      case "addOnServices":
        return addOnServicesList;
        break;
    }

    return null;
  }

  @override
  void initState() {
    super.initState();
    print(widget.type);

    dropdownItems = getListBasedOnName(widget.type);
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 8.0, 0, 10.0),
      child: Container(
        width: 325.0,
        height: 50.0,
        decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.black45,
              offset: Offset(2.5, 5.5),
              blurRadius: 5.0,
            )
          ],
          borderRadius: BorderRadius.circular(8),
          color: Colors.white,
        ),
        child: DropdownButtonHideUnderline(
          child: DropdownButton(
              value: selectedItem,
              hint: Padding(
                padding: const EdgeInsets.fromLTRB(22.0, 0, 0, 0),
                child: Text(
                  widget.dropdownText,
                  style: TextStyle(),
                ),
              ),
              items: dropdownItems.map((String value) {
                return new DropdownMenuItem<String>(
                  value: value,
                  child: new Text(value),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  selectedItem = value;
                });
              }),
        ),
      ),
    );
  }
}

Так как некоторые виджеты отсутствовали, я добавил свой, который вы можете изменить в соответствии с вашими потребностями. Сообщите мне, если это сработает.

...