This is my code
I want to put a var in dropdown list in flutter
new DropdownButton<String>(
// value: selectedPurpose,
hint: new Text(
'Select visitng purpose',
style: TextStyle(fontFamily: "Gotham"),
),
items: widget.size
.map((purposeTemp) {
return new DropdownMenuItem<String>(
value: purposeTemp,
child: new Text(
purposeTemp,
style: TextStyle(fontFamily: "Gotham"),
),
);
}).toList(),
onChanged: (String purpose) {
setState(() {
ss = purpose.toString();
});
},
// value: selectedPurpose,
)
am getting this error
type 'List<dynamic>' is not a subtype of type 'List<DropdownMenuItem<String>>'
what should I do to solve it
You can copy paste run full code below
You can use widget.size.map<DropdownMenuItem<String>>((String purposeTemp)
code snippet
items: widget.size.map<DropdownMenuItem<String>>((String purposeTemp) {
return DropdownMenuItem<String>(
value: purposeTemp,
child: Text(purposeTemp, style: TextStyle(fontFamily: "Gotham")),
);
}).toList(),
working demo
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: Center(
child: MyStatefulWidget(
size: ['One', 'Two', 'Free', 'Four'],
),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
List<String> size;
MyStatefulWidget({Key key, this.size}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
String selectedPurpose;
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: selectedPurpose,
style: TextStyle(color: Colors.deepPurple),
hint: Text(
'Select visitng purpose',
style: TextStyle(fontFamily: "Gotham"),
),
onChanged: (String Value) {
setState(() {
selectedPurpose = Value;
});
},
items: widget.size.map<DropdownMenuItem<String>>((String purposeTemp) {
return DropdownMenuItem<String>(
value: purposeTemp,
child: Text(purposeTemp, style: TextStyle(fontFamily: "Gotham")),
);
}).toList(),
);
}
}
Related
I am working with flutter. I create a DropDown menu in the menu_list.dart file. I want to use the value selected from the user in (menu_list.dart file) in the add_screen.dart file. So, that I can upload it in the FireStore with other user information. The code is attached below.
I am glad if someone helps.
'add_Screen.dart'
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:database/widgets/menu_list.dart';
import 'package:flutter/material.dart';
class AddScreen extends StatelessWidget {
String? personname, personphone, vall;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Add Data"),
),
body: Column(
children: [
Container(
child: MenuList(),
),
SizedBox(
height: 15,
),
Container(
child: TextFormField(
onChanged: (String name) {
getStudentName(name);
},
decoration: InputDecoration(
labelText: "Name",
focusedBorder: OutlineInputBorder(),
),
),
),
SizedBox(
height: 15,
),
Container(
child: TextFormField(
onChanged: (String phone) {
getStudentPhone(phone);
},
decoration: InputDecoration(
labelText: "PhoneNumber",
focusedBorder: OutlineInputBorder(),
),
),
),
SizedBox(
height: 15,
),
Container(
child: RaisedButton(
child: Text("Add"),
onPressed: createData,
),
),
],
),
);
}
createData() {
Future<void> documentReference = FirebaseFirestore.instance
.collection("Students")
.doc("subcollection")
.collection("collectionPath")
.doc()
.set(
{
"PersonName": personname,
"PersonPhone": personphone,
},
);
}
getStudentName(name) {
this.personname = name;
}
getStudentPhone(phone) {
this.personphone = phone;
}
}
`
----------------------------------------------------------------------------------------------
'menu_list.dart'
`
import 'package:flutter/material.dart';
class MenuList extends StatefulWidget {
const MenuList({Key? key}) : super(key: key);
#override
_MenuListState createState() => _MenuListState();
}
class _MenuListState extends State<MenuList> {
final items = ['Maths', 'Urdu', 'English', 'Simple'];
String? value;
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: value,
isExpanded: true,
items: items.map(buildMenuItem).toList(),
onChanged: (value) => setState(
() => this.value = value,
),
);
}
}
DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
value: item,
child: Text(
item,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30,
),
),
);
`
I think the best option for you, without overegineering the code, would be to pass a callback function that is received as parameter for the onChanged parameter of the DropdownButton.
It would look something like this:
In add_screen:
String _itemSelected;
MenuList(onChanged: (value) {
_itemSelected = value;
})
In menu_list:
class MenuList extends StatefulWidget {
final Function(String) onChanged;
const MenuList({required this.onChanged, Key? key}) : super(key: key);
#override
_MenuListState createState() => _MenuListState();
}
class _MenuListState extends State<MenuList> {
final items = ['Maths', 'Urdu', 'English', 'Simple'];
String? value;
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: value,
isExpanded: true,
items: items.map(buildMenuItem).toList(),
onChanged: widget.onChanged
);
}
}
I apologize if the code doesn't compile directly since I'm not able to compile it at the time.
Feel free to reach me if you have any questions
class AddScreen extends StatefulWidget {
#override
_AddScreenState createState() => _AddScreenState();
}
class _AddScreenState extends State<AddScreen> {
// make stateful
String? personname, personphone, vall, dropdownValue;
// define value for dropdownValue
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Add Data"),
),
body: Column(
children: [
Container(
child: MenuList(dropdownValue: dropdownValue),
// call MenuList as above passing dropdown value;
),
...
// other children
],
),
);
}
}
// menu_list.dart
import 'package:flutter/material.dart';
class MenuList extends StatefulWidget {
String dropdownValue;
// pass the value here
MenuList({Key? key, this.dropdownValue}) : super(key: key);
#override
_MenuListState createState() => _MenuListState();
}
class _MenuListState extends State<MenuList> {
final items = ['Maths', 'Urdu', 'English', 'Simple'];
// String? value;
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: widget.dropdownValue,
// set the value here
isExpanded: true,
items: items.map(buildMenuItem).toList(),
onChanged: (value) => setState(
() => widget.dropdownValue = value,
// set the value here
),
);
}
}
I wanted to show dialog in my application. How can i achieve this using flutter
You can use a PopupMenuButton (https://api.flutter.dev/flutter/material/PopupMenuButton-class.html) to achieve this in flutter.
See example code below:
PopupMenuButton<int>(
itemBuilder: (context) => [
const PopupMenuItem(
value: 1,
child: Center(
child: Icon(
Icons.download_outlined,
size: 30.0,
),
),
),
const PopupMenuItem(
value: 2,
child: Center(
child: Icon(
Icons.link,
size: 30.0,
),
),
),
const PopupMenuItem(
value: 2,
child: Center(
child: Icon(
Icons.share,
size: 30.0,
),
),
),
],
icon: const Icon(
Icons.more_horiz,
size: 40.0,
),
offset: const Offset(150, -150),
);
The above example popups a list of Icons when the PopupMenuButton is pressed.
You can adapt this to your use-case above.
Finally I found a Solution thanks enfinity. Here how i solve the problem.
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
);
}
}
/// An arbitrary widget that lives in a popup menu
class PopupMenuWidget<T> extends PopupMenuEntry<T> {
const PopupMenuWidget({ Key key, this.height, this.child }) : super(key: key);
#override
final Widget child;
#override
final double height;
#override
bool get enabled => false;
#override
_PopupMenuWidgetState createState() => new _PopupMenuWidgetState();
}
class _PopupMenuWidgetState extends State<PopupMenuWidget> {
#override
Widget build(BuildContext context) => widget.child;
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
actions: <Widget>[
new PopupMenuButton<String>(
onSelected: (String value) {
print("You selected $value");
},
itemBuilder: (BuildContext context) {
return [
new PopupMenuWidget(
height: 40.0,
child: new Row(
children: [
IconButton(
icon: Icon(
Icons.remove,
color: Colors.green,
),
onPressed: () {
print("Remove");
}),
Text("1"),
IconButton(
icon: Icon(
Icons.add,
color: Colors.green,
),
onPressed: () {
print("Add");
}),
],
),
),
];
}
),
],
),
);
}
}
I want to add new item in dropdown at runtime.
Center(
child: DropdownButtonHideUnderline(
child: DropdownButton(
isExpanded: true,
value: selectedClass,
items: _dropDownMenuItemsClass,
onChanged: changedDropDownItem,
),
))
Further an example if I understood your question correctly:
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String dropdownValue = 'One';
var values = <String>['One', 'Two', 'Free', 'Four'];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Title'),
),
body: Row(
children: [
DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: dropdownValue,
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: values.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
//Button to add/change value at runtime
RaisedButton(
child: Text('Change'),
onPressed: () {
setState(() {
values = values..add('Value');
});
},
)
],
));
}
}
var _currencies = ['Rupees', 'Dollars', 'Pounds'];
child: DropdownButton<String>(
items: _currencies.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
value: 'Rupees',
onChanged: (String newValueSelected) {
// Your code to execute, when a menu item is selected from dropdown
},
),
Create a variable you want add string.here i added var _currencies.
hope this will work for you.
I am building an app and in it, I have the names of people in a list from which I could add/delete, etc.. The problem is this list is not saved when I close the app, which is inconvenient.
I heard you can use shared Preferences to save simple objects like this, without complicating things like using SQLite and json.
So I'd like to know what's the suggested way to persist this data and load it etc.
Thanks in Advance and have a great day :)
Here is the code:
import 'package:flutter/material.dart';
import 'package:zakif_yomi3/NewPerson.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.purple,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<String> people = [];
void _addNewPerson(String name) {
setState(() {
people.add(name);
});
}
void _startAddNewPerson(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewPerson(_addNewPerson),
behavior: HitTestBehavior.opaque,
);
},
);
}
void _deletePerson(int value ) {
setState(() {
people.removeAt(value);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
'People',
style: TextStyle(fontSize: 30),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _startAddNewPerson(context),
)
],
),
body: ListView.builder(
itemCount: this.people.length,
itemBuilder: (context, value) {
return Card(
color: Colors.amberAccent[200],
elevation: 3,
child: Container(
child: ListTile(
leading: Text(value.toString()),
title: Text(
people[value],
),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
_deletePerson(value);
},
),
),
),
);
},
),
);
}
}
And the NewPerson object:
import 'package:flutter/material.dart';
class NewPerson extends StatefulWidget {
final Function addTx;
NewPerson(this.addTx);
#override
_NewPersonState createState() => _NewPersonState();
}
class _NewPersonState extends State<NewPerson> {
final _nameController = TextEditingController();
void _submitData() {
final name = _nameController.text;
widget.addTx(
name
);
Navigator.of(context).pop();
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Name'),
controller: _nameController,
onSubmitted: (_) => _submitData(),
),
RaisedButton(
child: Text('Add Person'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button.color,
onPressed: _submitData,
),
],
),
),
);
}
}
You could use this functions to persist and load data from shared preferences.
Get SharedPreferences from here.
To persist data to SharedPreferences, called after adding or deleting a new element to the list.
_persistData() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.setStringList("persons", _people);
}
To load data from SharedPreferences, usually called in initState.
_loadData() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
_people = preferences.getStringList("persons");
});
}
How to make Stylish drop down and get data from that drop down list and display it as text. How can I achieve this task? Here is my code in which I am making a flutter app that is a spin the bottle game. I have made a drop down in it but, how to get its value and print as a text on screen:
import 'package:flutter/material.dart';
import 'dart:math';
List<DropdownMenuItem<String>> listDrop = [];
loadData() {
listDrop = [];
listDrop.add(new DropdownMenuItem(
child: new Text('Item 1'),
value: "1",
));
listDrop.add(new DropdownMenuItem(
child: new Text('Item 2'),
value: "2",
));
listDrop.add(new DropdownMenuItem(
child: new Text('Item 3'),
value: "3",
));
}
class ImageRotate extends StatefulWidget {
#override
_ImageRotateState createState() => new _ImageRotateState();
}
class _ImageRotateState extends State<ImageRotate>
with SingleTickerProviderStateMixin {
AnimationController animationController;
static var rng = new Random();
double random_number = 0.0;
);
} }
new Container(
alignment: Alignment.centerRight,
padding: new EdgeInsets.only(top: 200.0, right: 100.0),
child: new DropdownButton(
style: new TextStyle(
color: Colors.redAccent,
fontWeight: FontWeight.bold,
),
items: listDrop,
hint: new Text(
"Select"
),
onChanged: loadData(),
),
),
you code is not clear and cut so i added full example for you.
import 'package:flutter/material.dart';
void main() => runApp(Home());
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home:MultipleDropDownPage()
);
}
}
class MultipleDropDownPage extends StatefulWidget {
MultipleDropDownPage({Key key}) : super(key: key);
#override
_MultipleDropDownPageState createState() => new _MultipleDropDownPageState();
}
class _MultipleDropDownPageState extends State<MultipleDropDownPage> {
String selectedValues;
#override
void initState() {
// TODO: implement initState
super.initState();
selectedValues = "1";
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text('Multi Drop'),
),
body: Column(
children: <Widget>[
new Text(selectedValues.toString()),
new DropdownButton<String>(
onChanged: (String value) {
setState(() {
selectedValues = value;
});
},
hint: new Text('Course Unit'),
value: selectedValues,
items: <String>["1", "2", "3", "4", "5"].map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
});
},
),
);
}
}