трепетание: тип «Список <dynamic>» не является подтипом типа «Список» ' - PullRequest
0 голосов
/ 04 марта 2020

В моем приложении флаттера есть раскрывающийся список, и ниже показано, как я загружаю в него данные.

Consumer<ProductsImpl>(
                  builder: (context, data, child) {
                    print("consumer running");

                    return DropdownButton(
                        hint: Text(
                          "Please Select          ",
                          style: TextStyle(
                            fontSize: 14,
                          ),
                        ),
                        items: data.geProductAndTypeList.map((info) {
                          return DropdownMenuItem(
                            child: new Text(info,
                                style: TextStyle(
                                  fontSize: 14,
                                )),
                            value: data,
                          );
                        }).toList(),
                        onChanged: (String newValue) {
                          setState(() {
                            _productdropDown = newValue;
                            print(newValue);
                          });
                        },
                        value: _productdropDown);
                  },
                ),

Ниже приведен код, где вы можете найти getProductAndTypeList

class ProductsImpl with ChangeNotifier {
  NavLinks _navLinks = new NavLinks();

  List<FreshProducts> _freshProductList = [];

  List<String> _productAndTypeList = [];

  get geProductAndTypeList => _productAndTypeList;

  Future<void> geFreshProductsBySpecies(int id) async {
    try {
      var data = await http.get(_navLinks.getFreshProductsBySpecies(id));
      var jsonData = convert.json.decode(data.body).cast<Map<String, dynamic>>();
      _freshProductList = jsonData
          .map<FreshProducts>((json) => new FreshProducts.fromJson(json))
          .toList();

      print("Product sIZE: " + _freshProductList.length.toString());
    } catch (error) {
      throw error;
    }

    //notifyListeners();
  }

  Future<void> buildProductAndTypeList(int speciesID) async{

    print("asasas");

    for(int i=0; i < _freshProductList.length ; i++)
    {
      if(_freshProductList[i].productSpecies.idproductSpecies == speciesID)
      {
        String str = _freshProductList[i].productCategory.name + ", "+ _freshProductList[i].productType.type;

        if(!_productAndTypeList.contains(str))
        {
          _productAndTypeList.add(str);
          print(str);
        }
      }
    }

    notifyListeners();

  }
}

Когда строится выпадающий список, я получаю следующую ошибку:

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
[38;5;244mThe following assertion was thrown building Consumer<ProductsImpl>(dirty, dependencies: [_DefaultInheritedProviderScope<ProductsImpl>]):[39;49m
type 'List<dynamic>' is not a subtype of type 'List<DropdownMenuItem<String>>'


[38;5;248mEither the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
  https://github.com/flutter/flutter/issues/new?template=BUG.md
[39;49m

[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mConsumer<ProductsImpl>[39;49m
[38;5;244mWhen the exception was thrown, this was the stack[39;49m
[38;5;248m#0      ProductUIState._buildForm.<anonymous closure>[39;49m
[38;5;248m#1      Consumer.buildWithChild[39;49m
[38;5;248m#2      SingleChildStatelessWidget.build[39;49m
[38;5;244m#3      StatelessElement.build[39;49m
[38;5;248m#4      SingleChildStatelessElement.build[39;49m
[38;5;244m...[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

Как я могу решить эту проблему?

1 Ответ

0 голосов
/ 04 марта 2020

Ответ заключается в создании пользовательского метода get для _productAndTypeList с указанным типом возвращаемого значения. Когда используется get geProductAndTypeList => _productAndTypeList;, он возвращает динамический c.

. Я сделал следующий метод.

List<String> geProductAndTypeList()
  {
    return _productAndTypeList;
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...