I am new to flutter I have an API from sql server table with the following result:
[["Nom1", "Prénom1"], ["Nom2", "Prenom2"]]
api "http://192.168.2.220:5000/api/get_user"
I want to display the result in a dropdown menu dynamically
I am new to flutter I have an API from sql server table with the following result:
[["Nom1", "Prénom1"], ["Nom2", "Prenom2"]]
api "http://192.168.2.220:5000/api/get_user"
I want to display the result in a dropdown menu dynamically
CodePudding user response:
You need to create function to get the data from the API
List user_data = List();
String user_id;
void getUser() async {
var res = await http.get(
Uri.encodeFull("http://192.168.2.220:5000/api/get_user"),
headers: {"Accept": "application/json"}); //if you have any auth key place here
var response = json.decode(res.body);
setState(() {
user_data = response ;
});
}
You need to initiate it in initState
:
@override
void initState() {
// TODO: implement initState
super.initState();
this.getUser();
}
Then you can use it in your code by creating Dropdown Widget. I could not get what your first and second element means in your array, but logic should be like following:
DropdownButton(
items: user_data.map((item) {
return new DropdownMenuItem(
child: new Text(
item[
'field'], // names that the API dropdown contains
style: TextStyle(
fontSize: 13.0,
),
),
value: item['field']
.toString()
);
}).toList(),
onChanged: (String newValue) {
setState(() {
user_id = newValue;
});
},
value:
user_id,
)
CodePudding user response:
import "package:flutter/material.dart";
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(MaterialApp(
title: "operateur",
home: MyApp(),
));
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List user_data = List();
String user_id;
void getUser() async {
var res = await http.get(
Uri.encodeFull("http://192.168.2.220:5000/api/get_user"),
headers: {"Accept": "application/json"});
var response = json.decode(res.body);
setState(() {
user_data = response ;
print(user_data);
print(user_data.runtimeType);
});
}
@override
void initState() {
super.initState();
this.getUser();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
child: SingleChildScrollView(
child: Column(children: [
DropdownButton(
items: user_data.map((item){
return new DropdownMenuItem(
child: new Text(
item['field'],
style: TextStyle(fontSize: 13.0,),),
value: item['field'].toString());
}).toList(),
onChanged: (String newValue) {
setState(() {user_id = newValue;});
},
value:user_id,)
],) ,
) ,
),
);
}
}
I get this error
======== Exception caught by widgets library ==========================
The following _TypeError was thrown building MyApp(dirty, state: _MyAppState#a87ca):
type 'String' is not a subtype of type 'int' of 'index'