Невозможно создать выпадающую кнопку во флаттере - PullRequest
0 голосов
/ 29 апреля 2020

Я пытаюсь использовать выпадающий список из json во флаттере, но у меня ошибка, я не смог его увидеть:

    Widget _listaCiudades(){
    //citiesProvider.getCities().then((value) => print(value));
    return FutureBuilder(
      future: citiesProvider.getCities(),

      builder: (context, AsyncSnapshot <List<dynamic>> snapshot) {
        //print('project snapshot data is: ${snapshot.data}');

        return DropdownButton(
          style: TextStyle(
            fontFamily: 'Monserrat',
            fontStyle: FontStyle.normal,
            fontSize: 20,
          ),
            disabledHint: Text("You can't select anything."),
            items: snapshot.data.map((valorCity) {
              print(valorCity['name']);
              return DropdownMenuItem<String>(
                value: valorCity['pk'].toString(),
                child: Text(valorCity['name'].toString()),
              );
            }).toList(),//allCities(snapshot.data),
            onChanged: (String newValue) {
              setState(() {
               value = newValue;
              });
            }
        );
      },
    );
  }
}

Это вывод:

    Performing hot restart...
Syncing files to device Android SDK built for x86...
Restarted application in 5.373ms.

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<List<dynamic>>(dirty, state: _FutureBuilderState<List<dynamic>>#819ba):
The method 'map' was called on null.
Receiver: null
Tried calling: map<DropdownMenuItem<String>>(Closure: (dynamic) => DropdownMenuItem<String>)

The relevant error-causing widget was: 
  FutureBuilder<List<dynamic>> file:///C:/Users/FALABELLA/Desktop/Flutter/flutter-app-login-ui/lib/screens/signup_screen.dart:186:12
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      _SignupScreenState._listaCiudades.<anonymous closure> (package:app_login_ui/screens/signup_screen.dart:199:34)
#2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:732:55)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4623:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4506:15)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<List<dynamic>>(dirty, state: _FutureBuilderState<List<dynamic>>#819ba):
The method 'map' was called on null.
Receiver: null
Tried calling: map<DropdownMenuItem<String>>(Closure: (dynamic) => DropdownMenuItem<String>)

The relevant error-causing widget was: 
  FutureBuilder<List<dynamic>> file:///C:/Users/FALABELLA/Desktop/Flutter/flutter-app-login-ui/lib/screens/signup_screen.dart:186:12
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      _SignupScreenState._listaCiudades.<anonymous closure> (package:app_login_ui/screens/signup_screen.dart:199:34)
#2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:732:55)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4623:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4506:15)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter ( 7314): Aartselaar
I/flutter ( 7314): Abancay
I/flutter ( 7314): Abbotsford
I/flutter ( 7314): Abingdon
I/flutter ( 7314): Absecon
I/flutter ( 7314): Abu Dhabi
I/flutter ( 7314): Acacias
I/flutter ( 7314): Acarigua
I/flutter ( 7314): Adelaide
I/flutter ( 7314): Aeropuerto
I/flutter ( 7314): Agua
I/flutter ( 7314): Agua Amarilla
I/flutter ( 7314): Agua Fria
I/flutter ( 7314): Agua Salada

1 Ответ

0 голосов
/ 29 апреля 2020

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

if (snapshot.hasData) {
    return DropdownButton(
      ...
      ...
    );
}

И Вы также можете попробовать,

items: snapshot.data?.map((valorCity) {
            print(valorCity['name']);
            return new DropdownMenuItem<String>(
              value: valorCity['pk'].toString(),
              child: Text(valorCity['name'].toString()),
            );
          })?.toList() ?? [],
...