Выпадающее меню Flutter с базой данных HTTP

#json #flutter #drop-down-menu

#json #flutter #выпадающее меню

Вопрос:

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

 I/flutter (30929): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (30929): The following NoSuchMethodError was thrown building AddSubCategory(dirty, dependencies:
I/flutter (30929): [_ModalScopeStatus], state: _AddSubCategoryState#a24b3):
I/flutter (30929): The method 'map' was called on null.
I/flutter (30929): Receiver: null
I/flutter (30929): Tried calling: map<DropdownMenuItem<String>>(Closure: (dynamic) => DropdownMenuItem<String>)
I/flutter (30929):
I/flutter (30929): The relevant error-causing widget was:
I/flutter (30929):   AddSubCategory file:///D:/apps/reboo/lib/main.dart:45:46
I/flutter (30929): 
I/flutter (30929): When the exception was thrown, this was the stack:
I/flutter (30929): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
I/flutter (30929): #1      _AddSubCategoryState.build (package:reboo/screens/admin_screens/add_subcategory_screen.dart:272:37)
I/flutter (30929): #2      StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
I/flutter (30929): #3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4627:15)
I/flutter (30929): #4      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11)
I/flutter (30929): #5      Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)      
I/flutter (30929): #6      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4606:5)
I/flutter (30929): #7      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4791:11)
I/flutter (30929): #8      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
I/flutter (30929): ...     Normal element mounting (132 frames)
I/flutter (30929): #140    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
I/flutter (30929): #141    Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18) 
I/flutter (30929): #142    RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5705:32)
I/flutter (30929): #143    MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6246:17)
I/flutter (30929): #144    Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15) 
I/flutter (30929): #145    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (30929): #146    StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11)
I/flutter (30929): #147    Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)      
I/flutter (30929): #148    StatefulElement.update (package:flutter/src/widgets/framework.dart:4832:5)
I/flutter (30929): #149    Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15) 
I/flutter (30929): #150    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (30929): #151    Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)      
I/flutter (30929): #152    ProxyElement.update (package:flutter/src/widgets/framework.dart:4987:5)  
I/flutter (30929): #153    _InheritedNotifierElement.update (package:flutter/src/widgets/inherited_notifier.dart:183:11)
I/flutter (30929): #154    Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15) 
I/flutter (30929): #155    SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6125:14)
I/flutter (30929): #156    Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15) 
I/flutter (30929): #157    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (30929): #158    StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11)
I/flutter (30929): #159    Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)      
I/flutter (30929): #160    StatefulElement.update (package:flutter/src/widgets/framework.dart:4832:5)
I/flutter (30929): #161    Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15)
I/flutter (30929): #162    SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6125:14)
I/flutter (30929): #163    Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15) 
I/flutter (30929): #164    SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6125:14)
I/flutter (30929): #165    Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15) 
I/flutter (30929): #166    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (30929): #167    Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
I/flutter (30929): #168    StatelessElement.update (package:flutter/src/widgets/framework.dart:4708:5)
I/flutter (30929): #169    Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15) 
I/flutter (30929): #170    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (30929): #171    Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)      
I/flutter (30929): #172    ProxyElement.update (package:flutter/src/widgets/framework.dart:4987:5)  
I/flutter (30929): #173    Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15) 
I/flutter (30929): #174    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (30929): #175    StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11)
I/flutter (30929): #176    Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
I/flutter (30929): #177    BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2730:33)
I/flutter (30929): #178    WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:913:20)
I/flutter (30929): #179    RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:302:5)
I/flutter (30929): #180    SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15)
I/flutter (30929): #181    SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1055:9)
I/flutter (30929): #182    SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:971:5)
I/flutter (30929): #186    _invoke (dart:ui/hooks.dart:251:10)
I/flutter (30929): #187    _drawFrame (dart:ui/hooks.dart:209:3)
I/flutter (30929): (elided 3 frames from dart:async)
I/flutter (30929):
I/flutter (30929): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter (30929): {-MJld0iwmyBsLs3wwp17: {icon: https://some link, title: Beauty}, -MK9sJCCMTbvdzzUQZFl: {icon: https://https://some link, title: Fun amp; Adventure}}
I/flutter (30929): {-MJld0iwmyBsLs3wwp17: {icon: https://, title: Beauty}, -MK9sJCCMTbvdzzUQZFl: {icon: https://some link, title: Fun amp; Adventure}}
I/flutter (30929): Another exception was thrown: NoSuchMethodError: The method 'map' was called on null.
  

печать (resBody);

 I/flutter (30929): {-MJld0iwmyBsLs3wwp17: {icon: somelink.png, title: Beauty}}
  

Мой код JSON из базы данных

 {
  "category" : {
    "-MJld0iwmyBsLs3wwp17" : {
      "icon" : "https:https://Some link",
      "title" : "Beauty"
    },
    "-MK9sJCCMTbvdzzUQZFl" : {
      "icon" : "https://Some link",
      "title" : "Fun amp; Adventure"
    }
  }
}
  

Первая часть:

 class AddSubCategory extends StatefulWidget {
  static const routeName = '/addsubcategory';

  @override
  _AddSubCategoryState createState() => _AddSubCategoryState();
}

class _AddSubCategoryState extends State<AddSubCategory> {

final _form = GlobalKey<FormState>();

  String _mySelection;

  Map<String, dynamic> map;
  List<dynamic> data;

  Future<String> getSWData() async {
    final url = "some link";
    var response = await http.get(url);
    var resBody = json.decode(response.body) as Map<String, dynamic>;
    print(resBody);
    setState(() {
      map = resBody;
      data = map["id"];
      
    });

    print(map);
    return "Sucess";
  }

  @override
  void initState() {
    this.getSWData();
    super.initState();
  }
  

Часть для выпадающего списка

 DropdownButton(
 isDense: true,
      hint: new Text("Select Category"),
      items: data.map((item) {
      return new DropdownMenuItem(
       child: new Text(item['title']),
       value: item['id'].toString(),
     );
   }).toList(),
   onChanged: (newVal) {
    setState(() {
      _mySelection = newVal;
    });
  },
  value: _mySelection,
),
  

Комментарии:

1. элементы: data.map((элемент) Здесь ваши данные равны нулю. Можете ли вы отредактировать свой вопрос с помощью print(resBody);

2. Я / flutter (30929): {-MJld0iwmyBsLs3wwp17: {значок: somelink.png , заголовок: Красота}}

3. Попробуйте изменить это: data = map[«title»];

4. Я изменил его на «заголовок», но получаю аналогичную ошибку. (Я обновил новую ошибку в исходном сообщении)

Ответ №1:

data Переменная не содержит записи для 'id' .

Вот почему data установлено значение null , что приводит к ошибке.

Комментарии:

1. Спасибо за ваш ответ. Любые предложения о том, как я могу это решить?