首页 > 解决方案 > 我尝试使用颤振和json数据从rest api向DropDownButton显示数据,但它没有用

问题描述

我的代码:


    import 'package:flutter/material.dart';
    import 'package:shaal/module/home.dart';
    import 'package:shaal/controlers/databasehelper.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    import 'dart:io';
    import 'dart:convert';
    import 'package:http/http.dart' as http;
    import 'package:multi_image_picker/multi_image_picker.dart';
    import 'dart:async';
    import 'package:shaal/module/showdata.dart';

    class AddData extends StatefulWidget{

      AddData({Key key , this.title}) : super(key : key);
      final String title;

      @override
      AddDataState  createState() => AddDataState();

    }

    class AddDataState extends State<AddData> {

      List<Asset> images = List<Asset>();
      String _error;

      DatabaseHelper databaseHelper = new DatabaseHelper();


      final TextEditingController _nameController = new TextEditingController();
      final TextEditingController _priceController = new TextEditingController();
      final TextEditingController _descriptionController = new TextEditingController();
      final TextEditingController _quantityController = new TextEditingController();

      /*
      "currency_id": "1",
      "unit_id": "1",
      "case_id": "1",
      "price": "4",
      "name": "bysicle",
      "description": "it is new ",
      "quantity": "5",
      "country_id": "1",
      "category_id": "1"
    */

      String _mySelection;

      List country_data = List();

      String countryid;

      Future<String> country() async {
        final prefs = await SharedPreferences.getInstance();

        final key = 'session_id';
        final value = prefs.get(key ) ?? 0;

        var res = await http.get(
            Uri.encodeFull("http://husam.from-ar.com/api/api-ad/en/1"),
            headers: {"Accept": "application/json",
                     "Authorization" : "$value",
            }); //if you have any auth key place here...properly..
        var resBody = await json.decode(res.body);

        setState(()  {
          country_data =  resBody;

        });

        return "Sucess";
      }

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

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Add Product',
          home: Scaffold(
            body: SingleChildScrollView(
              child: Container(
                height: MediaQuery.of(context).size.height,
                child: new Stack(children: <Widget>[
              Positioned(
                 child: Container(
                   padding: EdgeInsets.only(top: 40),
                   child: Column(children: <Widget>[
                     Row(
                       mainAxisAlignment: MainAxisAlignment.spaceBetween,
                       children:
                       <Widget>[
                         IconButton(
                           onPressed: () {
                             Navigator.pop(context);
                           },
                           icon: Icon(Icons.arrow_back_ios),
                           iconSize: 30,
                           color: Colors.red[300],
                         ),
                       ],),
                     SizedBox(height: 30,),
                     SizedBox(
                       width: 400,
                       child: Card(
                         child: Container(
                           padding: EdgeInsets.only(left: 20, right: 20),
                           child: Column(children: <Widget>[
                              SizedBox(height: 9,),
                             TextField(
                               controller: _nameController,
                               obscureText: false,
                               autofocus: true,
                               cursorColor: Colors.black,
                               decoration: InputDecoration(
                                 labelStyle: TextStyle(
                                     color: Colors.black54
                                 ),
                                 border: InputBorder.none,
                                 focusedBorder: OutlineInputBorder(

                                     borderSide: BorderSide(color: Colors.red)
                                 ),
                                 icon: Icon(Icons.title,
                                   color: Colors.black45,

                                 ),


                                 labelText: 'Name',

                               ),
                             ),
                             SizedBox(height: 9,),
                             TextField(

                               obscureText: false,
                               cursorColor: Colors.black,
                               controller: _descriptionController,
                               decoration: InputDecoration(
                                 border: InputBorder.none,
                                 labelStyle: TextStyle(
                                     color: Colors.black54
                                 ),

                                 focusedBorder: OutlineInputBorder(
                                     borderSide: BorderSide(color: Colors.red)
                                 ),

                                 icon: Icon(Icons.description,
                                   color: Colors.black45,

                                 ),


                                 labelText: 'description',

                               ),
                             ),
                             SizedBox(height: 9,),

                             TextField(

                               obscureText: false,
                               cursorColor: Colors.black,
                               controller: _quantityController,
                               decoration: InputDecoration(
                                 border: InputBorder.none,
                                 labelStyle: TextStyle(
                                     color: Colors.black54
                                 ),

                                 focusedBorder: OutlineInputBorder(
                                     borderSide: BorderSide(color: Colors.red)
                                 ),

                                 icon: Icon(Icons.keyboard_hide,
                                   color: Colors.black45,

                                 ),


                                 labelText: 'quantity',

                               ),
                             ),
                            SizedBox(height: 9,),
                             TextField(

                               controller: _priceController,

                               cursorColor: Colors.black,
                               decoration: InputDecoration(
                                 border: InputBorder.none,
                                 labelStyle: TextStyle(
                                     color: Colors.black54
                                 ),

                                 focusedBorder: OutlineInputBorder(
                                     borderSide: BorderSide(color: Colors.red)
                                 ),

                                 icon: Icon(Icons.equalizer,
                                   color: Colors.black45,

                                 ),


                                 labelText: 'price',

                               ),
                             ),
                           ],
                           ),),

                       ),

                     ),

                   Column(
                     children: <Widget>[
    DecoratedBox(
                           decoration: BoxDecoration(
                               border: new Border.all(color: Colors.black),
                               borderRadius: BorderRadius.circular(5.0)),
                           child: Padding(
                             padding: EdgeInsets.fromLTRB(10, 5, 0, 0),
                             //Why you have used Stack ??????
                             //B'coz it make clickable to whole decorated Box!!!! as you can click anywhere for dropdown !!!
                             child: Stack(
                               children: <Widget>[

    //Country Text
                                 Text(
                                   "Country:  ",

                                   style: TextStyle(
                                     fontSize: 13.0,
                                   ),
                                 ),

    //Dropdown that has no loine beneath

                                 DropdownButtonHideUnderline(

                                   child:

    //starting the dropdown
                                   DropdownButton(
                                     items: country_data.map((item) {

                                       return new DropdownMenuItem(

                                           child: new Text(
                                             item['countries']['name'],    //Names that the api dropdown contains
                                             style: TextStyle(
                                               fontSize: 13.0,
                                             ),
                                           ),
                                           value: item['countries']['id'].toString()


                                          //e.g   India (Name)    and   its   ID (55fgf5f6frf56f) somethimg like that....
                                       );
                                     }).toList(),

                                     onChanged: (String newVal)  {
                                       setState(() {
                                        countryid = newVal;
                                         print(countryid.toString());
                                       });
                                     },

                                     value: countryid,           
                                   ),


                                 )
                               ],
                             ),
                           )),
                     ],
                   ),



                     Center(child: Text('Error: $_error')),
                     RaisedButton(
                       child: Text("Pick images"),
                       onPressed: loadAssets,
                     ),
                     Expanded(
                       child: buildGridView(),
                     ),










                     Container(
                       height: 50,
                       child: new RaisedButton(
                         onPressed: () {
                           databaseHelper.addData(_descriptionController.text.trim(),
                               _quantityController.text.trim(),
                               _nameController.text.trim(),
                               _priceController.text.trim());
                           Navigator.of(context).push(
                               new MaterialPageRoute(
                                 builder: (BuildContext context) => new Dashboard(),
                               )
                           );
                         },
                         color: Colors.red,
                         child: new Text(
                           'Add ad',
                           style: new TextStyle(
                               color: Colors.white,
                               backgroundColor: Colors.red),),
                       ),
                     ),


                   ],
                   ),
                 ),
              )

                ],),

              ),
            ),

          ),
        );














      }












      Widget buildGridView() {
        if (images != null)
          return GridView.count(
            crossAxisCount: 3,
            children: List.generate(images.length, (index) {
              Asset asset = images[index];
              return AssetThumb(
                asset: asset,
                width: 300,
                height: 300,
              );
            }),
          );
        else
          return Container(color: Colors.white);
      }


      Future<void> loadAssets() async {
        setState(() {
          images = List<Asset>();
        });

        List<Asset> resultList;
        String error;



        try {
          resultList = await MultiImagePicker.pickImages(
            maxImages: 6,
          );
        } on Exception catch (e) {
          error = e.toString();
        }

        // If the widget was removed from the tree while the asynchronous platform
        // message was in flight, we want to discard the reply rather than calling
        // setState to update our non-existent appearance.
        if (!mounted) return;

        setState(() {
          images = resultList;
          if (error == null) _error = 'No Error Dectected';
        });
      }











    }

我的 json 数据

{
    "products": [],
    "productStatus": [
        {
            "name": "OLD",
            "id": 1
        }
    ],
    "countries": [
        {
            "name": "Turkey",
            "id": 1
        },
        {
            "name": "Syria",
            "id": 2
        }
    ],
    "currencies": [
        {
            "name": "DOLLAR",
            "id": 1
        }
    ],
    "units": [
        {
            "name": "KG",
            "id": 1
        },
        {
            "name": "liter",
            "id": 2
        }
    ],
    "addresses": []
}

我隐藏了我的休息 api

引用我想在 DropDownButton 中显示数据,但它不起作用我的代码没有错误。我的 json 数据它的多个对象我打电话给他,我在调试器中播种了我的数据,但数据没有进入 DropDownButton 为什么我不知道,因为我没有看到任何错误。

标签: jsonapiflutter

解决方案


推荐阅读