API data not showing in flutter dropdown - flutter

i am trying to display data list API to dropdown but the result is not there, which i have to fix.
I'm trying to change or update user data and have some data in the form of a list including the user being able to choose country, religion, and others. among these
how do i make it.
fetch API
Future<UserBiodata> getBiodata() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/biodata',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
return UserBiodata.fromJson(jsonDecode(response.body));
} else {
throw Exception('Token Expired!');
}
}
show in widget
String? _mySelection;
List<Agama> agama = [];
#override
void initState() {
super.initState();
BiodataProvider().getBiodata();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(kToolbarHeight),
child: CustomAppbar(
title: 'Edit Biodata',
),
),
body: Padding(
padding: const EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.only(left: 12, right: 8),
width: double.infinity,
height: 50,
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 1,
blurRadius: 9,
offset: const Offset(
1,
2,
),
),
],
),
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
items: agama.map((item) {
return DropdownMenuItem<String>(
value: item.nmAgama,
child: Text(item.nmAgama),
);
}).toList(),
onChanged: (newVal) {
setState(() {
_mySelection = newVal!;
});
},
value: _mySelection,
),
),
),

using StateManagement or FutureBuilder to receive async data from Future function (BiodataProvider().getBiodata();)
read more at: https://dart.dev/codelabs/async-await
https://docs.flutter.dev/development/data-and-backend

you are using List<Agama> agama = []; to display the dropdown items, but you are not adding data to your agama list.
So, add the proper data into your agama list which you are getting from API.
And don't forget to do setState((){}) after adding data into agama list because you are not using any state management.

Here is a full example like you want.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter DropDownButton',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String? dropdownvalue;
Future<List<String>> getAllCategory() async {
var baseUrl = "https://gssskhokhar.com/api/classes/";
http.Response response = await http.get(Uri.parse(baseUrl));
if (response.statusCode == 200) {
List<String> items = [];
var jsonData = json.decode(response.body) as List;
for (var element in jsonData) {
items.add(element["ClassName"]);
}
return items;
} else {
throw response.statusCode;
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("DropDown List"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FutureBuilder<List<String>>(
future: getAllCategory(),
builder: (context, snapshot) {
if (snapshot.hasData) {
var data = snapshot.data!;
return DropdownButton(
// Initial Value
value: dropdownvalue ?? data[0],
// Down Arrow Icon
icon: const Icon(Icons.keyboard_arrow_down),
// Array list of items
items: data.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items),
);
}).toList(),
// After selecting the desired option,it will
// change button value to selected value
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
},
);
} else {
return const CircularProgressIndicator();
}
},
),
],
),
),
);
}
}

Related

Flutter Navigator.of(context).pushNamed not passing the argument to the next screen

I have the following problem with a List Tile screen, when you select the specific Tile it should pass the arguments to the next screen, I don't know what is missing, but the navigator is not passing the arguments and it is not reporting any error either.Here is the code:
Screen 4:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:australremote/screens/screen5.dart';
void main() {
runApp(
JobsListView(),
);
}
class Job {
final String ssid;
final String auth;
final String encry;
Job({required this.ssid, required this.auth,required this.encry});
factory Job.fromJson(Map<String, dynamic> json) {
return Job(
ssid: json['ssid'],
auth: json['auth'],
encry: json['encry'],
);
}
}
class JobsListView extends StatelessWidget {
const JobsListView({Key? key}) : super(key: key);
Future<List<Job>> _fetchJobs() async {
final response = await http
.get(
Uri.parse('http://10.10.10.254/httpapi.asp?command=wlanGetApListEx'));
if (response.statusCode == 200) {
final List jsonResponse = json.decode(response.body)['aplist'] as List;
return jsonResponse.map((job) => new Job.fromJson(job)).toList();
} else {
throw Exception('Failed to load jobs from API');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Finding your available networks',
style: TextStyle(color: Colors.black87)),
titleSpacing: 00.0,
centerTitle: true,
toolbarHeight: 60.2,
toolbarOpacity: 0.6,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(25),
bottomLeft: Radius.circular(25)),
),
elevation: 0.00,
backgroundColor: Colors.transparent,
),
body: SafeArea(
child: Column(
children: <Widget>[
Expanded(
child: FutureBuilder<List<Job>>(
future: _fetchJobs(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<Job> data = snapshot.data ?? [];
return _jobsListView(data);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Container(
alignment: Alignment.topCenter,
margin: EdgeInsets.only(top: 400),
child: CircularProgressIndicator(
backgroundColor: Colors.grey,
color: Colors.black,
),
);
},
),
),
],
),
),
);
}
ListView _jobsListView(data) {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return _tile(
context,
title: data[index].ssid,
subtitle: data[index].auth,
icon: Icons.wifi
);
});
}
ListTile _tile(BuildContext context, {required String title,required String subtitle,required IconData icon}) =>
ListTile(
title: Text(title,
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 20,
)),
subtitle: Text(subtitle),
leading: Icon(
icon,
color: Colors.grey[500],
),
trailing: Icon(
Icons.arrow_forward_ios,
),
onTap: ()
{
//Navigator.pushNamed(context, '/fifth');
print(title);
print(subtitle);
Navigator.of(context).pushNamed(
'/fifth',
arguments:[title,subtitle],
);
},
//TO DO: Pass the arguments selected to the next screen, and insert it into the URI
//TO DO:Hex to ASCII.
);
}
Screen 5:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:australremote/screens/screen4.dart';
void main() {
runApp(MyHomePage());
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _textController = TextEditingController();
final String? title = '';
final String? subtitle = '';
final String? encry= '';
#override
Widget build(BuildContext context) {
final args = ModalRoute.of(context)?.settings?.arguments;
print(title);
print(subtitle);
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Home wifi network:$title, Authentication: $subtitle'),
TextField(
controller: _textController,
decoration: InputDecoration(hintText: "Enter the password of your Wifi network"),
),
TextButton(
style: TextButton.styleFrom(
primary: Colors.blue,
),
onPressed: () async {
// You can get the entered text using the text controller
String enteredText = _textController.text;
// Send the text to the API using the http package
final response = await http.get(Uri.parse(
"http://10.10.10.254/httpapi.asp?command=wlanConnectApEx:ssid=$title:ch=1:auth=$subtitle:encry=:pwd=$enteredText:chext=1"),
//"text=$enteredText",
);
if (response.statusCode == 200) {
Navigator.pushNamed(context, '/');
} else {
// There was an error with the request
// You can handle the error here
}
},
child: Text("Connect"),
),
],
),
),
);
}
}
I set some prints on both screen to confirm that is not passing anything to the next screen.
You can try changing this line
final args = ModalRoute.of(context)?.settings?.arguments;
to
final args = ModalRoute.of(context)?.settings?.arguments as List<String>;
or
List<String> args = ModalRoute.of(context)?.settings?.arguments;
Casting like this might solve your problem.
This is like telling Flutter that the arguments you passed is a List.
Then you can access the args like args[0] and args[1].
You are not reading the title and subtitle.
final args = ModalRoute.of(context)?.settings?.arguments;
title = args['title'];
subtitle = args['subtitle'];
print(title);
print(subtitle);

The return type 'NewsModel' isn't a 'Widget' as required by the closure's context

I have been trying to build a News App that fetches data from the newsapi.org service and just when I am about to call the data inside the main method I am getting this error saying that my class 'NewsModel' isn't of the type 'Widget' as required by the closure's context. I have no idea what that means but here is my code for the app split into 2 files.
import 'package:flutter/material.dart';
import 'models/news_model.dart';
import 'news_service.dart';
import 'package:assgn_digia_tech/models/news_model.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _loading = true;
var newsList;
List<NewsModel> articles = [];
void getNews() async {
newsService apiNews = newsService();
await apiNews.getNews();
articles = apiNews.apiNews;
setState(() {
_loading = false;
});
}
#override
void initState() {
super.initState();
getNews();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
'News API',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
backgroundColor: Colors.cyan[50],
// ignore: prefer_const_literals_to_create_immutables
actions: [
Padding(
padding: const EdgeInsets.only(right: 12.0),
child: IconButton(
icon: Icon(Icons.search, color: Colors.black, size: 26),
onPressed: () {},
),
),
],
),
body: SafeArea(
child: _loading
? Center(
child: CircularProgressIndicator(),
)
: SingleChildScrollView(
child: Container(
child: Column(
children: [
Container(
child: ListView.builder(
itemCount: articles.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return NewsModel(
title: articles[index].title,
description: articles[index].description,
author: articles[index].author,
content: articles[index].content,
urlToImage: articles[index].urlToImage,
);
},
),
),
],
),
),
),
),
),
);
}
}
import 'dart:convert';
import 'package:assgn_digia_tech/models/news_model.dart';
import 'package:http/http.dart' as http;
class newsService {
List<NewsModel> apiNews = [];
Future<void> getNews() async {
String apiUrl =
'https://newsapi.org/v2/top-headlines?country=in&apiKey=4e3474bb91ec49eda31b75e2daf6da3c';
var response = await http.get(Uri.parse(apiUrl));
var jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
jsonData['articles'].forEach((element) {
if (element['urlToImage'] != null && element['description'] != null) {
NewsModel article = NewsModel(
title: element['title'],
author: element['author'],
description: element['description'],
urlToImage: element['urlToImage'],
content: element["content"],
);
apiNews.add(article);
}
});
}
}
}
itemBuilder: (context, index) {
return NewsModel(
You are supposed to return a Widget from the builder, because the purpose is to build a UI. Do you have a custom "NewsWidget" here, or do you want to build it from scratch? Maybe start by returning Text(articles[index].title) and then building it up from there to include all the other parts of your NewsModel.

How to get JSON response after onPresseed button in Flutter // Dart

I don't get any issues to get JSON data the button is pressed to get JSON response.body is printed successfully but the JSON response is executed before I give _addressController value the if condition executed so the exception is shown on the print state. so please see my code and help me to overcome the issues
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:core';
import 'dart:convert';
import 'package:http/http.dart'as http;
import 'string.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Retrieve Text Input',
home: MyCustomForm(),
);
}
}
class MyCustomForm extends StatefulWidget {
const MyCustomForm({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyCustomForm> {
final _formKey = GlobalKey<FormState>();
var url1 = 'This is my first off url';
var _addressControler = TextEditingController();
late Future<Balance> futureBalance;
#override
void initState() {
super.initState();
futureBalance = fetchBalance();
}
Future<Balance> fetchBalance() async {
http.Response response =
await http.get(Uri.parse(url1+_addressControler.text));
print(response.body);
if (response.statusCode == 200) {
return Balance.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load album');
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
key: _formKey,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
controller: _addressControler,
decoration: InputDecoration(
labelText: 'Enter the address...',
labelStyle: TextStyle(color: Colors.blue),
border: new OutlineInputBorder(
borderSide: new BorderSide(color: Colors.black)),),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () async {
await fetchBalance();
},
child: const Text('Submit'),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Text("${_addressControler.text}"),
),
Container(
//color: Colors.blueAccent,
child: FutureBuilder<Balance>(
future: futureBalance,
builder: (context, index) {
if (index.hasData) {
print(index.data!.height);
var x = (index.data!.result[0].amount);
var y = int.parse(x);
assert(y is int);
var z = (y / 1000000);
print(z);
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('${z.toString()}',
style: TextStyle(fontSize: 20,),),
]);
} else if (index.hasError) {
return Text("${index.error}");
}
return CircularProgressIndicator();
},
),
),
]
),
),
)
);
}
}
I have an issue on fetchBalance() function. The if the condition is executed before I click the onPressed button but I what to do after given TextField and submit onPressed to execute the condition. so, is any possible way to overcome this issue please help me...
I am not sure I understand your question, but it seems you get an error because fetchBalance is executed before you expect it to.
Well, you call futureBalance = fetchBalance(); within your initState() method, hence the code is executed when your widget is being initialized and not only after you press the button. This means, you try to parse the url without appending _addressControler.text.
also, you can use it like this.
fetchBalance().then((balance) {
setState(() {
_balance = balance; //need to create one variable of type Balance
});
});
Better put the setState() in your async call:
Future<Balance> fetchBalance() async {
http.Response response =
await http.get(Uri.parse(url1+_addressControler.text));
print(response.body);
if (response.statusCode == 200) {
setState(() {
_balance = Balance.fromJson(jsonDecode(response.body));
});
} else {
throw Exception('Failed to load album');
}
}
First up all I remove the initState() and i use setState() for onPressed() to call the API function fetchBalance() on the state it's working good..
child: ElevatedButton(
onPressed: () {
setState(() {
fetchBalance();
});
fetchBalance();
},
child: const Text('Submit'),
),
),

Flutter Error: Use api in tabbar and tabbarView?

I want to fetch data from API and use the data in tabbar and tabview.
I want to create (Ayurved app), I have a list of subcategory in the api, I followed this documentation, so I need to add api's subcategory to my TabBar.
So How can I do that? I don't understand how this will happen.
This is my Tab Page.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:hospital/customApiVariable.dart';
import 'package:http/http.dart' as http;
class TabPage extends StatefulWidget {
final medicineCatUniqId;
const TabPage({Key key, this.medicineCatUniqId}) : super(key: key);
// const TabPage({Key key}) : super(key: key);
#override
_TabPageState createState() => _TabPageState();
}
class _TabPageState extends State<TabPage> {
var response;
var medicineSubCategoryApi;
#override
void initState() {
// TODO: implement initState
//
super.initState();
// for loading
fetchData(widget.medicineCatUniqId);
}
fetchData(var medicineCatUniqId) async {
a2rTokenKey=carpet1234');
var api = Uri.parse(
'$baseUrl/productSubCatApi.php?a2rTokenKey=$a2rTokenKey&pcat=$medicineCatUniqId');
response = await http.get(
api,
);
print("medicineCatApiLnk " + api.toString());
print("medicineCat" + response.body);
medicineSubCategoryApi = jsonDecode(response.body);
print("medicineCatString" + medicineSubCategoryApi.toString());
setState(() {});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: medicineSubCategoryApi.length,
child: Scaffold(
appBar: AppBar(
title: const Text('Tabbed AppBar'),
bottom: TabBar(
isScrollable: true,
tabs: medicineSubCategoryApi.map((choice) {
return Tab(
text: choice.psubCatName,
icon: Icon(choice),
);
}).toList(),
),
),
body: TabBarView(
children: medicineSubCategoryApi.map<Widget>((choice) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: ChoicePage(
choice: choice,
),
);
}).toList(),
),
),
),
);
}
}
class ChoicePage extends StatelessWidget {
const ChoicePage({Key key, this.choice}) : super(key: key);
final choice;
#override
Widget build(BuildContext context) {
final TextStyle textStyle = Theme.of(context).textTheme.display1;
return Card(
color: Colors.white,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
// Icon(
// choice,
// size: 150.0,
// color: textStyle.color,
// ),
Text(
choice.psubCatName,
style: textStyle,
),
],
),
),
);
}
}
This is my Api Data.
[{"psubCatUniq":"60c464556cd04","psubCatName":"TURMERIC CAPSULES","psubCatDescrition":"TURMERIC CAPSULES","psubCatImg":"http:\/\/a2rstore.com\/inventory\/images\/subCategory-bb.jpg","psubCatIcon":"","psubCatDate":"","psubCatlink":"list.php?subName=TURMERIC CAPSULES&sub=60c464556cd04","pcatUniq":"60c462501a664","pcatName":"Herbal Tablets"},{"psubCatUniq":"60c464360de3f","psubCatName":"PAIN CALM TABLET","psubCatDescrition":"PAIN CALM TABLET","psubCatImg":"http:\/\/a2rstore.com\/inventory\/images\/subCategory-aa.jpg","psubCatIcon":"","psubCatDate":"","psubCatlink":"list.php?subName=PAIN CALM TABLET&sub=60c464360de3f","pcatUniq":"60c462501a664","pcatName":"Herbal Tablets"}]
You can use a FutureBuilder widget to make the API call then access the data you require from the response data to create the Tabs.
A Simple Example
#override
Widget build(BuildContext context) {
return MaterialApp(
home: FutureBuilder(
future: fetchData(widget.medicineCatUniqId),
builder: (context, snapshot) {
if (snapshot.hasData) {
// API data will be stored as snapshot.data
return DefaultTabController(
// Your Widget UI here ( Copy & paste ) what you have above
);
} else if (snapshot.hasError) {
return Text('Error');
} else {
return Text('Loading');
}
}
),
);
}
You will also need to update fetchData() to return the value to FutureBuilder:
fetchData(var medicineCatUniqId) async {
var api = Uri.parse(
'$baseUrl/productSubCatApi.php?a2rTokenKey=$a2rTokenKey&pcat=$medicineCatUniqId');
response = await http.get(
api,
);
print("medicineCatApiLnk " + api.toString());
print("medicineCat" + response.body);
medicineSubCategoryApi = jsonDecode(response.body);
print("medicineCatString" + medicineSubCategoryApi.toString());
//setState(() {});
return medicineSubCategoryApi;
}

Flutter DropdownButtonFormField is not working

I'm trying to populate the drop down by fetching the values from API.
When I click the drop down,the values are being shown,when I try to select a value,following error is thrown
items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1': is not true.
values in the list are not empty
When I tried to remove 'value' property of drop down, the error is not shown but the drop down is not showing the selected value
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:something/Utils/formServices.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';
import 'package:intl/intl.dart';
import 'dart:convert';
String insurer;
String package;
List insCat = List();
List insurers = List();
List<DropdownMenuItem> items = [];
class AddOrEditPack extends StatefulWidget{
#override
AddOrEditPackState createState() =>AddOrEditPackState();
}
class AddOrEditPackState extends State<AddOrEditPack>{
final formKey = GlobalKey<FormState>();
String insuranceCategory = ' ';
#override
void initState() {
getCategories();
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Contact Us'),
),
drawer: Drawer(
child: ListView(
children: <Widget>[
ListTile(
title: Text("Home"),
),
],
),
),
body:
Form(
key:formKey,
child: ListView(
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
child: DropdownButtonFormField<String>(
hint:Text('Insurance Category'),
items: insCat.map((item) {
return new DropdownMenuItem<String>(
child: new Text(item['name']),
// value: item['name'],
);
}).toList(),
onChanged: (String newValue) {
setState(() { insuranceCategory = newValue; });
print(newValue);
},
// value: insuranceCategory,
),
),
Padding(
padding: EdgeInsets.fromLTRB(10, 10, 10,0),
child: RaisedButton(
onPressed: () {
contact();
},
child: Text('Submit'),
),
)
],
),
)
),
);
}
getCategories() async{
var resp = await
http.get('http://192.168.4.101:3000/category/getCategoryList');
print(resp.body);
insCat = json.decode(resp.body);
setState(() {
insuranceCategory=insCat[0]['name'];
});
}
}
This is what the API is returning.
[
{"_id":"5d8dad3a2fcb272b7c0e74b5","name":"life insurance"},
{"_id":"5d8dad502fcb272b7c0e74b6","name":"vehicle insurance"},
{"_id":"5d8dadb22fcb272b7c0e74b9","name":"life insurance"}
]
Output:
void main() => runApp(MaterialApp(
title: "Hospital Management",
home: MyApp(),
));
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _mySelection = "2";
final String url = "http://webmyls.com/php/getdata.php";
List data = List(); //edited line
List<DropdownMenuItem> items = [];
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;
items = data.map((item) => DropdownMenuItem(child: Text(item['item_name']), value: item['id'].toString())).toList();
_mySelection = data[0]["id"];
});
print(resBody);
return "Sucess";
}
#override
void initState() {
super.initState();
this.getSWData();
}
#override
Widget build(BuildContext context) {
print("CoolTag: ${data.length}");
return Scaffold(
appBar: AppBar(title: Text("Hospital Management")),
body: Center(
child: DropdownButton(
items: items,
value: _mySelection,
onChanged: (newVal) {
setState(() {
_mySelection = newVal;
});
},
),
),
);
}
}