How to add different images in a dropdown in flutter - flutter

I tried to do a dropdown menu like this:
I found this exemple in stackoverflow to add image in dropdown but currently it's a list and I don't know how add different images
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
#override
_TestState createState() => new _TestState();
}
class _TestState extends State<Test> {
var _img = new
Image.network("https://upload.wikimedia.org/wikipedia/commons/thumb/8/89/TUCPamplona10.svg/500px-TUCPamplona10.svg.png");
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text("Test Drop"),),
body: new Center(
child: new Container (
height: 50.0,
child:new DropdownButton(
items: new List.generate(10, (int index){
return new DropdownMenuItem(child: new Container(
padding: const EdgeInsets.only(bottom: 5.0),
height: 100.0,
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_img,
new Text("Under 10")
],
),
));
})
, onChanged: null),),
),
);
}
}

I did it with JSON. you can call multiple values inside dropdown.
import "package:flutter/material.dart";
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class TestApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<TestApp> {
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: Row(
children: <Widget>[
Text(item['item_name']),
],
),
value: item['id'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
_mySelection = newVal;
});
},
value: _mySelection,
),
),
);
}
}
modify this,
children: <Widget>[
Text(item['item_name']),
Text(item['item_name']),
Text(item['item_name']),
],

Related

API data not showing in flutter dropdown

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

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 change an image when I click a toggle button(flutter)

enter image description here
I cannot embed image because I don't have 10 reputation.
I want to load image when I click toggle buttons. it seems simple for you but it is hard for me to do it. I am a beginner .
I don't know how to write onPressed button. I already wrote onPressed buttons for toggle button. it seems like it is not possible to write one more oppressed code. I already used the onpressedbutton code to use ToggleButton, but I need one more function to load image but I don't know how to do it
enter code here
import 'package:flutter/material.dart';
import '123.dart';
import '456.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('imageToggle'),),
body: Column(
children: [
Expanded(child: Image.asset('images/meow.jpg')),
Button123(
),
Button456(),
],
),
),
);
}
}
class Button456 extends StatefulWidget {
#override
_Button456State createState() => _Button456State();
}
class _Button456State extends State<Button456> {
List<bool> isSelected = List.generate(3, (index) => false);
#override
Widget build(BuildContext context) {
return Container(
child: ToggleButtons(
isSelected: isSelected,
color: Colors.black,
fillColor: Colors.grey,
children: [
Padding(padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text('cat1'),),
Padding(padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text('cat2'),),
Padding(padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text('cat3'),),
],
onPressed: (int newIndexx) {
setState(() {
for (int index = 0; index < isSelected.length; index++) {
if (index == newIndexx) {
isSelected[index] = true;
} else {
isSelected[index] = false;
}
}
});
},
)
);
}
}
You can make the image url a variable.
String imageLink = 'myImage.png';
class _MyAppState extends State<MyApp> {
onButtonPressed(String value) {
setState(() {imageLink = value});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('imageToggle'),),
body: Column(
children: [
Expanded(child: Image.asset(imageLink)),
TextButton(child: Text('Click Me!'), onPressed: onButtonPressed('newImageLink')),
],
),
),
);
}
}

Flutter Navdrawer disappears when I navigate from screen within screen

When I click on the drawer item (homepage) it works fine and I can access the drawer from appbar of homepage screen. Now the problem is when I navigate from the homepage to another screen (beginner plan),
the drawer disappears.
Navdrawer.dart code
import 'package:fitnessapp/components/constants.dart';
import 'package:fitnessapp/screens/NavPages/beginnerplan.dart';
import 'package:fitnessapp/screens/NavPages/running.dart';
import 'NavPages/homepage.dart';
import 'NavPages/profile.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:flutter/material.dart';
class DrawerItem {
String title;
IconData icon;
DrawerItem(this.title, this.icon);
}
class navdrawer extends StatefulWidget {
final drawerItems = [
new DrawerItem("Home Page", Icons.home),
new DrawerItem("Profile", Icons.account_circle),
new DrawerItem("Running", Icons.directions_run),
];
#override
State<StatefulWidget> createState() {
return new navdrawerState();
}
}
class navdrawerState extends State<navdrawer> {
int _selectedDrawerIndex = 0;
navdrawerState();
_getDrawerItemWidget(int pos) {
switch (pos) {
case 0:
return new homepage();
case 1:
return new profilepage();
case 2:
return new RunningPage();
default:
return Container();
}
}
onSelectItem(int index) {
setState(() => _selectedDrawerIndex = index);
Navigator.of(context).pop(); // close the drawer
}
#override
Widget build(BuildContext context) {
var drawerOptions = <Widget>[];
for (var i = 0; i < widget.drawerItems.length; i++) {
var d = widget.drawerItems[i];
drawerOptions.add(new ListTile(
leading: new Icon(d.icon),
title: new Text(d.title),
selected: i == _selectedDrawerIndex,
onTap: () => onSelectItem(i),
));
}
return new Scaffold(
appBar: new AppBar(
// here we display the title corresponding to the fragment
// you can instead choose to have a static title
title: new Text(widget.drawerItems[_selectedDrawerIndex].title),
),
drawer: new Drawer(
child: Column(
children: [
Expanded(flex: 1, child: UserHeader()),
Expanded(
flex: 2,
child: new Column(children: drawerOptions),
)
],
),
),
body: _getDrawerItemWidget(_selectedDrawerIndex),
);
}
}
class UserHeader extends StatelessWidget {
const UserHeader({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
color: mainaccent,
width: MediaQuery.of(context).size.width * 0.85,
child: DrawerHeader(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/minerva_tp.png"),
fit: BoxFit.cover)),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 50,
),
Text(
"Shahroz Javed",
style: TextStyle(color: Colors.white,fontSize: 20),
),
Text(
"shahrozjaved39#gmail.com",
style: TextStyle(color: Colors.white,fontSize: 15),
),
],
),
),
);
}
}
homepage.dart code for navgiation to biggenerplan
ontap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => beginnerplan()),
);
beginnerplan.dart code
import 'package:fitnessapp/screens/Navdrawer.dart';
import 'package:flutter/material.dart';
class beginnerplan extends StatefulWidget {
#override
_beginnerplanState createState() => _beginnerplanState();
}
class _beginnerplanState extends State<beginnerplan> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Text("Beginner plan"),
);
}
}

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