且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Flutter列表中使用JSON数据列表创建DropdownButton

更新时间:2023-11-25 07:54:34

只需检查一下我使用json创建的以下示例,我已经在本地解析了json:

Just Check out the following example i have created using the json, i have parsed the json locally :

以下是json:

{
    "objects": [
        {
            "id": "e20c",
            "name": "Apples",
            "type": "fruit"
        },
        {
            "id": "a24e",
            "name": "Oranges",
            "type": "fruit"
        },
        {
            "id": "f2a0",
            "name": "Bananas",
            "type": "fruit"
        }
    ],
    "from": 1,
    "to": 3,
    "total": 3
}

根据json,我创建了模型类:

Depending on the json i have created the model class :

// To parse this JSON data, do
//
//     final fruitResponse = fruitResponseFromJson(jsonString);

import 'dart:convert';

FruitResponse fruitResponseFromJson(String str) => FruitResponse.fromJson(json.decode(str));

String fruitResponseToJson(FruitResponse data) => json.encode(data.toJson());

class FruitResponse {
    List<Object> objects;
    int from;
    int to;
    int total;

    FruitResponse({
        this.objects,
        this.from,
        this.to,
        this.total,
    });

    factory FruitResponse.fromJson(Map<String, dynamic> json) => FruitResponse(
        objects: List<Object>.from(json["objects"].map((x) => Object.fromJson(x))),
        from: json["from"],
        to: json["to"],
        total: json["total"],
    );

    Map<String, dynamic> toJson() => {
        "objects": List<dynamic>.from(objects.map((x) => x.toJson())),
        "from": from,
        "to": to,
        "total": total,
    };
}

class Object {
    String id;
    String name;
    String type;

    Object({
        this.id,
        this.name,
        this.type,
    });

    factory Object.fromJson(Map<String, dynamic> json) => Object(
        id: json["id"],
        name: json["name"],
        type: json["type"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "type": type,
    };
}

后来是我定义下拉列表的主类:

And later the main class where the i have defined the dropdown :

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

import 'dummy.dart';

main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _UploadImageState createState() => _UploadImageState();
}

class _UploadImageState extends State<MyApp> {
  bool _isLoading = false;
  List<Object> objectList = List();

  Future<String> loadFromAssets() async {
    return await rootBundle.loadString('json/parse.json');
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadYourData();
  }

  loadYourData() async {
    setState(() {
      _isLoading = true;
    });

    String jsonString = await loadFromAssets();
    final fruitResponse = fruitResponseFromJson(jsonString);
    objectList = fruitResponse.objects;
    setState(() {
      _isLoading = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    String selectedFruit;

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Container(
            child: Padding(
              padding: const EdgeInsets.all(30.0),
              child: Container(
                height: 50,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5.0),
                  border: Border.all(
                      color: Colors.red, style: BorderStyle.solid, width: 0.80),
                ),
                child: DropdownButton(
                    value: selectedFruit,
                    isExpanded: true,
                    icon: Padding(
                      padding: const EdgeInsets.only(left: 15.0),
                      child: Icon(Icons.arrow_drop_down),
                    ),
                    iconSize: 25,
                    underline: SizedBox(),
                    onChanged: (newValue) {
                      setState(() {
                        print(newValue);
                        selectedFruit = newValue;
                      });
                      print(selectedFruit);
                    },
                    hint: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text('Select'),
                    ),
                    items: objectList.map((data) {
                      return DropdownMenuItem(
                        value: data.id.toString(),
                        child: Padding(
                          padding: const EdgeInsets.only(left: 10.0),
                          child: Text(
                            data.name,
                            style: TextStyle(
                              fontSize: 18,
                              color: Colors.black,
                            ),
                          ),
                        ),
                      );
                    }).toList()),
              ),
            ),
          ),
        ),
      ),
    );
  }
}