Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdown option data in flutter from json api [closed]

Tags:

flutter

dart

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

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

How to write the code to show the data from the API?

like image 367
user2468312 Avatar asked Aug 30 '18 09:08

user2468312


People also ask

How do you get the dropdown value in flutter?

Step 1: Add a variable called dropdownValue that holds the currently selected item. Step 2: Add the DropdownButton widget to your page. Step 3: Inside the DropdownButton, add the value parameter and assign the dropdownValue that we created in step 1.

How do you drop down in flutter?

DropDownButton: In Flutter, A DropDownButton is a material design button. The DropDownButton is a widget that we can use to select one unique value from a set of values. It lets the user select one value from a number of items. The default value shows the currently selected value.

How do I open dropdown dialog below DropdownButton flutter?

Option 1: Set DropDown. dart selectedItemOffset to -40 in then DropDownItems will always opens below the DropdownButton .


1 Answers

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,
        ),
      ),
    );
  }
}

enter image description here Do you want to achieve something else?

like image 134
Dinesh Balasubramanian Avatar answered Nov 25 '22 03:11

Dinesh Balasubramanian