Just 3 weeks into flutter-dart programming so I'm still a rookie.
I'm implementing a user Settings screen where the user's information is displayed.
The user can modify their information such as their first/last name and address.
I want the user's current name to be displayed as an initial value and as soon as the user modifies the field, I want to keep the change visible inside the TextField until they press the 'Update' button (see animation below). However, whenever the user changes, for example their first name, the initial value is shown again and their changes are lost (see animation below).
My TextField code for first name (last name and address are implemented similarly):
TextField(
onChanged: (text) => {},
textAlign: TextAlign.center,
controller: _firstNameController..text = userRep.firstName,
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]'))
],
onSubmitted: (text) {
setState(() {
_firstNameController.text = text;
});
},
style: GoogleFonts.lato(
fontSize: 16.0
)
)
and the controller is defined at the beginning of the class:
final TextEditingController _firstNameController = TextEditingController();
currently under testing so I use a user mocking with defaulted values.
here is the app's current behavior:
any ideas, please?
edit: after #AndreaCostanzo1 's answer, I'm adding more info and code portion about my work:
The TextField in question is inside the build method of
class _UserSettingsScreenState extends State<UserSettingsScreen>:
class _UserSettingsScreenState extends State<UserSettingsScreen> {
final GlobalKey<ScaffoldState> _scaffoldKeyUserScreenSet = new GlobalKey<ScaffoldState>();
final TextEditingController _firstNameController = TextEditingController();
final TextEditingController _lastNameController = TextEditingController();
final TextEditingController _addressController = TextEditingController();
final TextEditingController _creditCardController = TextEditingController();
#override
Widget build(BuildContext context) {
return Material(
color: Colors.lightGreen,
child: Consumer<UserRepository>(
builder:(context, userRep, _) {
return Scaffold(
resizeToAvoidBottomInset: false,
resizeToAvoidBottomPadding: false,
backgroundColor: Colors.lightGreen[600],
key: _scaffoldKeyUserScreenSet,
appBar: AppBar(
backgroundColor: Colors.lightGreen[900],
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: null //TODO: implement navigation drawer
),
title: Text("Settings"),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 20,),
CircularProfileAvatar(
userRep.avatarURL ??
'https://www.flaticon.com/svg/static/icons/svg/848/848043.svg',
borderColor: Colors.red,
radius: MediaQuery.of(context).size.height * 0.1,
initialsText: Text(
"Press to change",
textAlign: TextAlign.center,
style: GoogleFonts.lato()
),
onTap: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (BuildContext context) {
return Container(
height: 117,
child: Column(
textDirection: TextDirection.ltr,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ListTile(
tileColor: Colors.white,
leading: Icon(
Icons.photo_camera,
color: Colors.red,
),
title: Text("Take a new photo",
style: GoogleFonts.lato(),
),
onTap: () async {
PickedFile photo = await ImagePicker()
.getImage(source: ImageSource.camera);
if (null == photo) {
Scaffold.of(context).showSnackBar(
SnackBar(content:
Text("No image selected",
style: GoogleFonts.notoSans(fontSize: 18.0),
),
behavior: SnackBarBehavior.floating,
)
);
} else {
setState(() {
userRep.avatarURL = photo.path;
});
}
},
),
ListTile(
tileColor: Colors.white,
leading: Icon(
Icons.photo_size_select_actual_rounded,
color: Colors.red,
),
title: Text("Select from gallery",
style: GoogleFonts.lato(),
),
onTap: () async {
PickedFile photo = await ImagePicker()
.getImage(source: ImageSource.gallery);
if (null == photo) {
Scaffold.of(context).showSnackBar(
SnackBar(content:
Text("No image selected",
style: GoogleFonts.notoSans(fontSize: 18.0),
),
behavior: SnackBarBehavior.floating,
)
);
} else {
setState(() {
userRep.avatarURL = photo.path;
});
}
},
),
],
),
);
}
); //showModalBottomSheet
},
),
SizedBox(height: 30,),
Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: Container(
width: MediaQuery.of(context).size.width * 0.25,
height: MediaQuery.of(context).size.height * 0.1,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: SizedBox(
height: 200.0,
width: 100,
child: Text('First name',
style: GoogleFonts.montserrat(
fontSize: 16.0
),
textAlign: TextAlign.center,
),
),
),
Expanded(
flex: 3,
child: SizedBox(
height: 200.0,
width: MediaQuery.of(context).size.width * 0.5 - 10,
child: TextField(
onChanged: (text) => {},
textAlign: TextAlign.center,
controller: _firstNameController..text = userRep.firstName,
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]'))
],
onSubmitted: (text) {
setState(() {
_firstNameController.text = text;
});
},
style: GoogleFonts.lato(
fontSize: 16.0
)
),
),
),
],
),
),
),
and the UserRepository mock looks like this:
thank you everybody in advance!
After you call setState the widget tree is rebuilt. Since you gave us just a smaller fragment of code, I can't tell for sure if this is the portion of code that generates this issue.
controller: _firstNameController..text = userRep.firstName,
However, from the video I can tell you that, after calling submit (when the widget tree is rebuilt) you are setting back the value to its original state.
If you want to give an initial state to the textfield, do this:
initState(){
super.initState();
_firstNameController=TextEditingController();
_firstNameController.text = userRep.firstName,
}
And in the text field just use
controller: _firstNameController,
Also, remember to dismiss the controller when the widget is disposed:
dispose(){
_firstNameController.dispose();
}
Related
I want that Cancellation charges and the bottom button remains fixed on screen, while the Choose Seat(s) and passengers should be scrollable. But, whenever I am trying to insert any widget after singlechildscrollview, it is not appearing at the bottom.
As, my column has 3 widgets, a row, singlechildscrollview and button, so my button and top row should remain there and remaining seats and passengers should be scrollable, but I am not able to see the bottom button, while my row working fine, remaining there.
Code -
showCancellationCharges(BuildContext? context) {
final DateTime currentDate = DateTime.now();
if (ticketData!.data!.booking!.boarding!.eta! >
currentDate.millisecondsSinceEpoch)
showModalBottomSheet(
backgroundColor: Colors.white,
context: context!,
builder: (context) => Wrap(
children: [
StatefulBuilder(
builder: (context, stateSetter) => Padding(
padding: MediaQuery.of(context).viewInsets,
child: Container(
//height: MediaQuery.of(context).size.height*0.7,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(top: 5.0, bottom: 5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Cancellation Charges',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
)
),
IconButton(
icon: Icon(
Icons.close,
color: colorPrimary,
),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
),
Container(
height: MediaQuery.of(context).size.height*0.5,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'Choose Seat(s)',
style: TextStyle(color: popUpLightTextColor),
),
),
Column(
children: List.generate(
ticketData!.data!.booking!.seats!.length,
(index) => CancellationItem(
checkBoxState: ticketData!.data!.booking!
.seats![index].selected,
checkBox: (v) => stateSetter(() {
print('seat at index $index $v');
if (v)
totalSeatToCancel++;
else
totalSeatToCancel--;
ticketData!.data!.booking!.seats![index]
.selected = v;
}),
// checkBoxState: data[index.],
imagePath:
'assets/icons/ticket_seat_icon.svg',
title: ticketData!
.data!.booking!.seats![index].code,
)),
),
// CancellationSeatItems(
// data: ticketData.data.booking.seats,
// ),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'Choose Passenger(s)',
style: TextStyle(color: popUpLightTextColor),
),
),
Column(
children: List.generate(
ticketData!.data!.booking!.passengers!.length,
(index) => CancellationItem(
checkBoxState: ticketData!.data!.booking!
.passengers![index].selected,
checkBox: (v) => stateSetter(() {
if (v)
totalPassengerToCancel++;
else
totalPassengerToCancel--;
print('passenger at index $index $v');
ticketData!.data!.booking!
.passengers![index].selected = v;
}),
imagePath: (ticketData!.data!.booking!
.passengers![index].gender ==
'MALE')
? 'assets/icons/male_icon.svg'
: 'assets/icons/female_icon.svg',
title: ticketData!.data!.booking!
.passengers![index].name,
)),
),
],
),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Container(
child: ValueListenableBuilder(
valueListenable: isCalculating,
builder: (BuildContext context, bool val, Widget? child) {
return FlatButton(
height: 44,
minWidth: MediaQuery.of(context).size.width,
color: val ? Colors.grey : colorPrimary,
onPressed: () => calculateItem(),
child: Text(
val ? 'Calculating...' : 'Calculate',
style: TextStyle(
color: Colors.white,
fontSize: 16
),
),
);
},
),
),
),
// CancellationPassengerItems(
// data: ticketData.data.booking.passengers,
// ),
],
),
),
),
),
),
],
));
else
_snackbarService.showSnackbar(
message: 'Sorry, ticket can not be cancelled');
}
Actually I solved the problem. I just used isScrollControlled: true, parameter for showModalBottomSheet and it's done.
you may put the listview inside a container with a height
I am currently building a botcoin ticker app that returns a list of currencies to a dropDown menu .
I am getting the following errors:-
error: The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type. (body_might_complete_normally at [bitcoin_ticker] lib\price_screen.dart:10)
error: The argument type 'List<DropdownMenuItem>' can't be assigned to the parameter type 'List<DropdownMenuItem>?'. (argument_type_not_assignable at [bitcoin_ticker] lib\price_screen.dart:60)
Here is my code
import 'package:flutter/material.dart';
import 'coin_data.dart';
int i = 0;
class PriceScreen extends StatefulWidget {
#override
_PriceScreenState createState() => _PriceScreenState();
}
List<DropdownMenuItem> getDropDownItems() {
List<DropdownMenuItem<String>> dropdownItem = [];
for (String currency in currenciesList) {
DropdownMenuItem(
child: Text(currency), //
value: currency,
);
}
}
class _PriceScreenState extends State<PriceScreen> {
late String selectedCurrency = 'USD';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('đ€ Coin Ticker'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
child: Card(
color: Colors.lightBlueAccent,
elevation: 5.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 28.0),
child: Text(
'1 BTC = ? USD',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
),
),
),
),
),
Container(
height: 150.0,
alignment: Alignment.center,
padding: EdgeInsets.only(bottom: 30.0),
color: Colors.lightBlue,
child: DropdownButton<String>(
value:selectedCurrency,//Default value
items: getDropDownItems(),
onChanged:(value){//it is like an on Pressed Button
setState(() {
selectedCurrency = value!;
print(selectedCurrency);
});
},
),
),
],
),
);
}
}
The warning shows because the getDropDownItems doesn't returning anything from the function. Also you are not updating the list in the for loop. you can refer the following code
List<DropdownMenuItem> getDropDownItems() {
List<DropdownMenuItem> dropdownItem = currenciesList
.map((currency) => DropdownMenuItem(
child: Text(currency), //
value: currency,
))
.toList();
return dropdownItem;
}
I try to collect data in firestore from my Flutter app. With the following code: my question is how to display a error message when the user didn't choose an item on DropdownMenuItem?
body: Form(
key: _formKeyValue,
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 12.0),
children: <Widget>[
SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton(
items: _specialite
.map((value) => DropdownMenuItem(
child: Text(
value,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black),
),
value: value,
))
.toList(),
onChanged: (selectedAccountType) {
print('$selectedAccountType');
setState(() {
medicalType = selectedAccountType;
});
},
value: medicalType,
isExpanded: false,
hint: Text(
'choisissez la spécialité',
style: TextStyle(color: Colors.black),
),
)
],
),
....
....
i used this answer https://stackoverflow.com/a/59746301/15400156 but nothing displayed on screen.
You can make the first menu item called "Select xxx", which is also the default item (index 0), then you can check the index when the user hit "Submit" button.
You can achieve this in different ways.Remove value property from DropDownButton and initialize medicalType with String medicalType;. Then on submit button press, check if medicalType is null or not. Below is the full code.
class MyWidget extends StatefulWidget {
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
List<String> _specialite = ["abc", "def", 'ghi'];
String medicalType;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Form(
// key: _formKeyValue,
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 12.0),
children: <Widget>[
SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton(
items: _specialite
.map((value) => DropdownMenuItem(
child: Text(
value,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
value: value,
))
.toList(),
onChanged: (String selectedAccountType) {
print('$selectedAccountType');
setState(() {
medicalType = selectedAccountType;
});
},
// value: medicalType,
isExpanded: false,
hint: Text(
'choisissez la spécialité',
style: TextStyle(color: Colors.black),
),
)
],
),
ElevatedButton(
onPressed: () {
if (medicalType == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("please choose medical type")));
}
},
child: Text("submit"))
]),
));
}
}
i'm trying to show the data i retrieve on a function outside of it (to show in a listview of products) but i cant do it because i cant access the variable.
First I open a dialog where i put the order number, when i click a button on this dialog it runs the following code:
(this function is inside a onPressed).
Future loadProdutos() async{
ProdutosList produtosList =
ProdutosList.fromJson(response.data);
print(produtosList.produtos[1].qtd);
print(produtosList.produtos.length);
}
setState(() {
loadProdutos();
Navigator.pop(context, true);
});
So the data its stored on produtoslist, but when I try to use the produtosList length on the listview (for example) like the example below it cant access the data.
Here
child: ListView.builder(
itemCount: produtosList.produtos.length, <<< //Undefined name 'produtosList'.
Try correcting the name to one that is defined, or defining the name.dart(undefined_identifi
How can I make produtosList accessable from the whole file?
Or to create it outside of the function and use it inside (when i try i cant access the variable inside of the function, maybe because its async).
Heres the full code
class OS extends StatefulWidget {
#override
_OSState createState() => _OSState();
}
class _OSState extends State<OS> {
static _read() async {
final prefs = await SharedPreferences.getInstance();
final key = 'operador';
final value = prefs.getString(key);
print('saved tester $value');
String operadorLogado = value;
return operadorLogado;
}
#override
final _numeroOsController = TextEditingController();
void initState() {
super.initState();
_read();
var produtosList1 = <ProdutoOs>[];
//WidgetsBinding.instance.addPostFrameCallback((_) => _read());
// final prefs = await SharedPreferences.getInstance();
// final key = 'usuario';
// final value = prefs.getString(key);
// print('saved $value');
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("OS NÂș xxx"),
actions: <Widget>[
Padding(
padding: EdgeInsets.only(right: 20.0),
child: GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
scrollable: true,
title: Text('BUSCAR OS'),
content: Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
child: TextFormField(
controller: _numeroOsController,
decoration: InputDecoration(
icon: Icon(Icons.search),
),
),
),
),
actions: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.blue,
onPrimary: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32.0),
),
),
child: Text("IR"),
onPressed: () async {
Response response;
Dio dio = new Dio();
String url =
'http://192.168.15.2:8090/api/getOs';
response = await dio.post(url, data: {
"numeroos": _numeroOsController.text
});
print(response.statusCode);
jsonDecode(response);
Future loadProdutos() async {
ProdutosList produtosList =
ProdutosList.fromJson(response.data);
print(produtosList.produtos[1].qtd);
print(produtosList.produtos.length);
}
setState(() {
loadProdutos();
Navigator.pop(context, true);
});
},
)
]);
});
},
child: Icon(
Icons.search,
size: 26.0,
),
)),
],
),
body: Column(
children: [
Container(
color: Colors.blue,
child: Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Row(
children: [
Expanded(
flex: 8,
child: Text(
"CLIENTE:",
style: TextStyle(color: Colors.white),
),
),
Expanded(
flex: 8,
child: Text(
"STATUS:",
style: TextStyle(color: Colors.white),
),
),
],
),
),
),
Container(
color: Colors.blue,
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 8.0, 0, 8.0),
child: Row(
children: <Widget>[
Expanded(
flex: 2,
child: Text("CĂDIGO",
style: TextStyle(fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis),
),
Expanded(
flex: 1,
child: Text(
"QTD",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
flex: 3,
child: Text(
"FUNCIONĂRIO",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
flex: 4,
child: Text(
"DESCRIĂĂO",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
),
),
Divider(
height: 5.0,
),
Expanded(
child: ListView.builder(
itemCount: 3,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.fromLTRB(0.0, 4.0, 0.0, 4.0),
child: Row(
children: <Widget>[
Expanded(
flex: 2,
child: Text(
"12345",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
flex: 1,
child: Text(
"12",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
flex: 3,
child: Text("example",
style: TextStyle(fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis
),
),
Expanded(
flex: 4,
child: Text(
"DESCRIĂĂO DA PEĂA XXXXXX11111111 XXXXXXX",
style: TextStyle(fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis),
),
],
),
);
}),
)
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
scrollable: true,
title: Text('ADICIONAR PEĂA'),
content: Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(
icon: Icon(Icons.search),
),
),
],
),
),
),
actions: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.blue,
onPrimary: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32.0),
),
),
child: Text("IR"),
onPressed: () {
// your code
}),
],
);
});
},
child: Icon(Icons.add)),
);
}
}
Declare a local variable in class.
For example:
class PhotosScreen {
final photos = <Photo>[];
Future<void> reloadPhotos() async {
photos.clear();
photos.addAll(await api.getPhotos());
setState(() {});
}
}
In your case (you placed a variable to method, not to class):
var produtosList1 = <ProdutoOs>[];
#override
final _numeroOsController = TextEditingController();
void initState() {
super.initState();
}
I am developing an app with a dropdown. Below is my code. I have removed the UI design code to isolate the dropdown section itself.
class ShoppingCartUIState extends State<ShoppingCartUI> {
final _formKey = GlobalKey<FormState>();
String _checkoutDropdownValue=null;
//**UI design Code Removed**//
_showCheckoutPopup() {
String date=DateTime.now().toString();
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)), //this right here
child: Container(
height: MediaQuery.of(context).size.height/3,
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Container(
margin: EdgeInsets.all(10),
child: Text(
"What is Your Required Delivery Date?",
style: Theme.of(context).textTheme.subtitle,
),)
],
),
Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.calendar_today),
color: Colors.green,
onPressed: () {
date = "111";
},
),
Text(date)
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(top:20, left:10),
child: Text(
"What is your Airport of delivery?",
style: Theme.of(context).textTheme.subtitle,
),)
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(top:5, left:10),
child: DropdownButton(
hint: Text(
"Please Select ",
style: TextStyle(
fontSize: 14,
),
),
items: <String>[
'Skinless Boneless, Full Loins',
'brown',
'silver'
].map((data) {
return DropdownMenuItem(
child: new Text(data,
style: Theme.of(context).textTheme.body1),
value: data,
);
}).toList(),
onChanged: (String newValue) {
setState(() {
_checkoutDropdownValue = newValue;
print(newValue);
});
},
value: _checkoutDropdownValue),
)
],
),
],
),
));
}
#override
void initState() {
// TODO: implement initState
super.initState();
}
}
The issue is when I change the dropdown item, the new value never get selected. The previously selected value is always displayed. However since i am using a print when dropdown is done, I can see the item has changed.
How can I solved this issue?
Wrap your Dialog widget with StatefulBuilder to rebuild the dialog.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyPage(), //TODO: Add Scaffold
);
}
}
class MyPage extends StatefulWidget {
#override
_MyPageState createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> {
String date = "";
String _checkoutDropdownValue;
_showCheckoutPopup() {
return StatefulBuilder(
builder: (context, setState){
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
), //this r// ight here
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
margin: EdgeInsets.all(10),
alignment: Alignment.centerLeft,
child: Text(
"What is Your Required Delivery Date?",
style: Theme.of(context).textTheme.subtitle,
),
),
Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.calendar_today),
color: Colors.green,
onPressed: () {
setState(() {
date = "111";
});
},
),
Text(date)
],
),
Container(
margin: EdgeInsets.only(top: 20, left: 10),
alignment: Alignment.centerLeft,
child: Text(
"What is your Airport of delivery?",
style: Theme.of(context).textTheme.subtitle,
),
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 5, left: 10),
child: DropdownButton<String>(
hint: Text(
"Please Select ",
style: TextStyle(
fontSize: 14,
),
),
items: <String>[
'Skinless Boneless, Full Loins',
'brown',
'silver'
].map((data) {
return DropdownMenuItem(
child: new Text(data,
style: Theme.of(context).textTheme.body1),
value: data,
);
}).toList(),
onChanged: (String newValue) {
setState(() {
_checkoutDropdownValue = newValue;
});
},
value: _checkoutDropdownValue,
),
)
],
),
],
),
),
);
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
child: Text("Click Here"),
onPressed: () {
showDialog(
context: context,
builder: (context) => _showCheckoutPopup(),
);
},
),
),
);
}
}
can you change your onPressed to print(_checkoutDropdownValue); instead of print(newValue); that way we can see if there is a problem with the assignment