Dropdown option data in flutter from json api

前端 未结 1 1950
夕颜
夕颜 2021-01-01 01:14

I am newbie to Flutter development.

I want to retrieve data from the api and show in the flutter drop down options.

Api - http://webmyls.com/php/getdata.php

相关标签:
1条回答
  • 2021-01-01 01:57

    I am using your code only and edit just one line and it works like charm.

    import "package:flutter/material.dart";
    import 'dart:async';
    import 'dart:convert';
    import 'package:http/http.dart' as http;
    
    void main() => runApp(MaterialApp(
          title: "Hospital Management",
          home: MyApp(),
        ));
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      String _mySelection;
    
      final String url = "http://webmyls.com/php/getdata.php";
    
      List data = List(); //edited line
    
      Future<String> getSWData() async {
        var res = await http
            .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
        var resBody = json.decode(res.body);
    
        setState(() {
          data = resBody;
        });
    
        print(resBody);
    
        return "Sucess";
      }
    
      @override
      void initState() {
        super.initState();
        this.getSWData();
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: AppBar(
            title: Text("Hospital Management"),
          ),
          body: new Center(
            child: new DropdownButton(
              items: data.map((item) {
                return new DropdownMenuItem(
                  child: new Text(item['item_name']),
                  value: item['id'].toString(),
                );
              }).toList(),
              onChanged: (newVal) {
                setState(() {
                  _mySelection = newVal;
                });
              },
              value: _mySelection,
            ),
          ),
        );
      }
    }
    

    Do you want to achieve something else?

    0 讨论(0)
提交回复
热议问题