iam new to flutter and i would like to add a text under a button, but i cant seems to do it, so far here's my result
..
i use two Rows for the button and the text,
as you guys can see the text isnt align really well, i tried using ElevatedButton but the text is beside the button not below it.
this is my code so far:
import 'package:flutter/material.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:medreminder/NewsArticle/news_home.dart';
import 'Reminder/ui/home_reminder.dart';
import 'Reminder/ui/widgets/button.dart';
import 'package:medreminder/main_reminder.dart';
import 'package:medreminder/home_page.dart';
void main() {
// debugPaintSizeEnabled = true;
runApp(const HomePage());
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Medicine Reminder App'),
),
body: Column(
children: [
Stack(
children: [
Image.asset(
'images/MenuImg.jpg',
width: 600,
height: 170,
fit: BoxFit.cover,
),
],
),
const SizedBox(height: 10.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
IconButton(
icon: Image.asset('images/reminder.png'),
iconSize: 50,
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => const ReminderHomePage()),
);
},
),
IconButton(
icon: Image.asset('images/news.png'),
iconSize: 50,
onPressed: () {},
),
IconButton(
icon: Image.asset('images/recipe.png'),
iconSize: 50,
onPressed: () {},
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text("Reminder"),
Text("News"),
Text("Recipe")
],
)
],
),
),
);
}
}
if anyone know how to do it, please help. it will mean so much to me. thank you
try to put each iconButton inside a Column with its Text widget, try this code:
import 'package:flutter/material.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:medreminder/NewsArticle/news_home.dart';
import 'Reminder/ui/home_reminder.dart';
import 'Reminder/ui/widgets/button.dart';
import 'package:medreminder/main_reminder.dart';
import 'package:medreminder/home_page.dart';
void main() {
// debugPaintSizeEnabled = true;
runApp(const HomePage());
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Medicine Reminder App'),
),
body: Column(
children: [
Stack(
children: [
Image.asset(
'images/MenuImg.jpg',
width: 600,
height: 170,
fit: BoxFit.cover,
),
],
),
const SizedBox(height: 10.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
IconButton(
icon: Image.asset('images/reminder.png'),
iconSize: 50,
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => const ReminderHomePage()),
);
},
),
Text("Reminder")
],
),
Column(
children: [
IconButton(
icon: Image.asset('images/news.png'),
iconSize: 50,
onPressed: () {},
),
Text("News")
],
),
Column(
children: [
IconButton(
icon: Image.asset('images/recipe.png'),
iconSize: 50,
onPressed: () {},
),
Text("Recipe")
],
),
],
),
// Row(
// mainAxisAlignment: MainAxisAlignment.,
// children: [, , ],
// )
],
),
),
);
}
}
You can adjust Layout by using Row and Column
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Column(
children: [
const SizedBox(height: 10.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_showButton('assets/images/image1.jpg', 'Reminder'),
_showButton('assets/images/image2.jpg', 'News'),
_showButton('assets/images/image2.jpg', 'Recipe'),
],
),
],
),
),
);
}
_showButton(String imagePath, String text) {
return Column(
children: [
IconButton(
icon: Image.asset(imagePath),
iconSize: 50,
onPressed: () {
// Navigator.of(context, rootNavigator: true).push(
// MaterialPageRoute(builder: (context) => const ReminderHomePage()),
// );
},
),
Text(
text,
textAlign: TextAlign.center,
)
],
);
}
if u want to change the colour of the text button u can, its just commented out for you
import 'package:flutter/material.dart';
void main() {
// debugPaintSizeEnabled = true;
runApp(const HomePage());
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Medicine Reminder App'),
),
body: Column(
children: [
Stack(
children: [
Image.asset(
'images/MenuImg.jpg',
width: 600,
height: 170,
fit: BoxFit.cover,
),
],
),
const SizedBox(height: 10.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
IconButton(
icon: Image.asset('images/reminder.png'),
iconSize: 50,
onPressed: () {
// Navigator.of(context, rootNavigator: true).push(
// MaterialPageRoute(
// builder: (context) => const ReminderHomePage()),
// );
},
),
TextButton(
onPressed: () => print('reminder'),
child: Text(
'Reminder',
//style: TextStyle(color: Colors.black),
))
],
),
Column(
children: [
IconButton(
icon: Image.asset('images/news.png'),
iconSize: 50,
onPressed: () {},
),
TextButton(
onPressed: () => print('News'),
child: Text(
'News',
// style: TextStyle(color: Colors.black),
))
],
),
Column(
children: [
IconButton(
icon: Image.asset('images/recipe.png'),
iconSize: 50,
onPressed: () {},
),
TextButton(
onPressed: () => print('Recipe'),
child: Text(
'Recipe',
style: TextStyle(color: Colors.black),
))
],
),
],
),
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// children: [Text("Reminder"), Text("News"), Text("Recipe")],
// )
],
),
),
);
}
}
Try below code hope its helpful to you, I have try it two ways Using Column Widget and Gridview.builder(). Just replace my images with your image
1. Using Column Widget
Padding(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: const [
ImageRow(
imageUrl:
'https://cdn.iconscout.com/icon/free/png-256/reminder-1605670-1361019.png',
imageName: 'Reminder',
),
ImageRow(
imageUrl: 'https://cdn-icons-png.flaticon.com/512/21/21601.png',
imageName: 'News',
),
ImageRow(
imageUrl:
'https://cdn-icons-png.flaticon.com/512/1041/1041373.png',
imageName: 'Recipe',
),
],
),
),
ImageRow Class:
class ImageRow extends StatelessWidget {
const ImageRow({
Key? key,
required this.imageName,
required this.imageUrl,
}) : super(key: key);
final String imageUrl;
final String imageName;
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image.network(
imageUrl,
height: 50,
),
const SizedBox(
height: 5,
),
Text(imageName),
],
);
}
}
2. Using Gridview.builder()
Declare List on your imageName and imageUrl
List medicineInfo = [
{
'imageUrl':
'https://cdn.iconscout.com/icon/free/png-256/reminder-1605670-1361019.png',
'imageName': 'Reminder',
},
{
'imageUrl': 'https://cdn-icons-png.flaticon.com/512/21/21601.png',
'imageName': 'News',
},
{
'imageUrl': 'https://cdn-icons-png.flaticon.com/512/1041/1041373.png',
'imageName': 'Recipe',
},
];
GridView Widget:
Padding(
padding: const EdgeInsets.all(20),
child: GridView.builder(
shrinkWrap: true,
itemCount: medicineInfo.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 20,
),
itemBuilder: (context, index) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image.network(
medicineInfo[index]['imageUrl'],
height: 50,
),
const SizedBox(
height: 5,
),
Text(
medicineInfo[index]['imageName'],
),
],
);
},
),
),
Result Screen->
Related
iam still new in flutter and i wanted to make a homepage with a button and a listview in my app. so here is my expected homepage that i already designed
Expected design
as you guys can see i wanted to have a listvew in the button half of my homepage, and a boxdecoration with buttons infront of an image in the top half.
but so far my homepage looks like this
Actual homepage so far
here is my code for the homepage so far
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:medreminder/NewsArticle/news_home.dart';
import 'package:medreminder/Reminder/ui/theme.dart';
import 'Reminder/home_reminder.dart';
import 'Reminder/ui/widgets/button.dart';
import 'package:medreminder/main.dart';
import 'package:medreminder/home_page.dart';
void main() {
// debugPaintSizeEnabled = true;
runApp(const HomePage());
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: context.theme.backgroundColor,
appBar: AppBar(
backgroundColor: Color(0XFF0080FE),
title: const Text('Medicine Reminder App'),
),
body: Column(
children: [
Stack(
children: [
Image.asset(
'images/MenuImg.jpg',
width: 600,
height: 170,
fit: BoxFit.cover,
),
],
),
const SizedBox(height: 15.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
IconButton(
icon: Image.asset('images/reminder.png'),
iconSize: 50,
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => const ReminderHomePage()),
);
},
),
Text("Reminder\n", style: normalStyle,)
],
),
Column(
children: [
IconButton(
icon: Image.asset('images/news.png'),
iconSize: 50,
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => const NewsHomePage()),
);
},
),
Text(" News \n& Article", style: normalStyle)
],
),
Column(
children: [
IconButton(
icon: Image.asset('images/recipe.png'),
iconSize: 50,
onPressed: () {},
),
Text("Healty Food \n Recipe", style: normalStyle)
],
),
],
),
],
),
),
);
}
}
any help would mean so much to me, thank you guys
Please read more about Container's boxDecoration and ListView widgets
ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: 5,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
borderRadius: BorderRadius.circular(20)),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Container(
height: 50,
width: 50,
decoration: BoxDecoration(boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 1,
blurRadius: 1,
// offset: Offset(0,
// 1), // changes position of shadow
),
], color: Colors.white),
),
),
SizedBox(
width: 10,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [Text('Title'), Text('SubTitle')],
)
],
),
),
),
);
},
)
OUTPUT:
I am a beginner in Flutter and i am creating an demo application but in that application I want to add another card in the list widget(code is mentioned below) but somehow it shows an error.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class Intro extends StatefulWidget {
const Intro({Key? key}) : super(key: key);
#override
_IntroState createState() => _IntroState();
}
class _IntroState extends State<Intro> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children:
List<Widget>[
Container(
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Center(
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
title: Text('Goal'),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
child: const Text('>'),
onPressed: () {
showAlertDialog(context);
},
),
const SizedBox(width: 8),
],
),
],
),
),
),
),
),
Container(
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Center(
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
title: Text('objective'),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
child: const Text('>'),
onPressed: () {
showAlertDialog1(context);
},
),
const SizedBox(width: 8),
],
),
],
),
),
),
),
),
]
)
);
}
}
showAlertDialog(BuildContext context) {
// Create button
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop(MaterialPageRoute(builder: (context) => Intro()));
},
);
// Create AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Simple Alert"),
content: Text("This is an alert message."),
actions: [
okButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
showAlertDialog1(BuildContext context) {
// Create button
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop(MaterialPageRoute(builder: (context) => Intro()));
},
);
// Create AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Simple Alert"),
content: Text("This is an alert message."),
actions: [
okButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
Also , I tried by creating a loop of widget still it shows an error in Widget build(BuildContext context)!
So show me a way to run this code successfully!
Remove List<widget> after Column( children:
Try this code:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class Intro extends StatefulWidget {
const Intro({Key? key}) : super(key: key);
#override
_IntroState createState() => _IntroState();
}
class _IntroState extends State<Intro> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children:[
Container(
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Center(
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
title: Text('Goal'),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
child: const Text('>'),
onPressed: () {
showAlertDialog(context);
},
),
const SizedBox(width: 8),
],
),
],
),
),
),
),
),
Container(
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Center(
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
title: Text('objective'),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
child: const Text('>'),
onPressed: () {
showAlertDialog1(context);
},
),
const SizedBox(width: 8),
],
),
],
),
),
),
),
),
]
)
);
}}}
i have list item on my screen ... All I want to know is, how to add dynamicaly a list item on pressing a floatingActionbutton....
here is a first screen on which i have a button (for adding one more item like above item)
in this picture after selecting suit id .. i want when i pressed add button a copy of naap widget displays from which i can select 2ndsuit id...
i read a tutorial from medium.com but there he used sijmply two text boxes whixh is very easy..whereas in my situation it is pretty difficult for me.... but the situation is same .. you can also visit https://medium.com/#anilpandey071999/dynamically-adding-widgets-on-buttons-on-pressed-function-in-flutter-4d9f139744c7
following is my code...
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
import 'package:flutter_auth/Screens/Dashboard/DashboardScreen.dart';
import 'package:flutter_auth/Screens/SearchCustomer/SearchCustomerScreen.dart';
import 'package:flutter_auth/components/NavDrawer.dart';
import 'package:flutter_auth/components/bottombar.dart';
import 'package:flutter_auth/components/rounded_button.dart';
import 'package:flutter_auth/components/rounded_input_field.dart';
import 'package:flutter_auth/components/drop_down_list.dart';
import 'package:flutter_auth/Screens/Welcome/welcome_screen.dart';
import '../../constants.dart';
import 'components/inputtextfieldname.dart';
import 'components/inputtextfieldnumber.dart';
class AddCustomerScreen extends StatefulWidget {
#override
_AddCustomerScreenState createState() => _AddCustomerScreenState();
}
class _AddCustomerScreenState extends State<AddCustomerScreen> {
final CategoriesScroller categoriesScroller = CategoriesScroller();
ScrollController controller = ScrollController();
bool closeTopContainer = false;
double topContainer = 0;
List<Widget> itemsData = [];
void getPostsData() {
List<AddCustomerScreen> dynamicList = [];
List<dynamic> responseList = Customer_Data;
List<Widget> listItems = [];
responseList.forEach((post) {
listItems.add(GestureDetector(
onTap: () {
// _navigateAndDisplaySelection(context);
},
child: Container(
height: 200,
margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20.0)), color: Colors.white, boxShadow: [
BoxShadow(color: Colors.black.withAlpha(100), blurRadius: 10.0),
]),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
post["name"], textAlign: TextAlign.center,
style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold,color: kPrimaryColor),
),
// Expanded(child: drop_down_list())
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding:EdgeInsets.symmetric(horizontal:10.0),
child:Container(
height:2.0,
width:275.0,
color:kPrimaryColor),),
],),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(onPressed: (){}, icon: Icon(Icons.camera_alt_rounded), iconSize: 30,color: Color(0XFFc49864)),
IconButton(onPressed: (){}, icon: Icon(Icons.add_photo_alternate_outlined), iconSize: 30,color: Color(0XFFc49864))
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(child: drop_down_list())
])
],),
)),));
});
setState(() {
itemsData = listItems;
});
}
#override
void initState() {
super.initState();
getPostsData();
controller.addListener(() {
setState(() {
});
});
}
#override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
final double categoryHeight = size.height*0.30;
return SafeArea(
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Add Customer'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.home,),
onPressed: (){Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return WelcomeScreen();
},
),
);},
)
]
),
drawer: NavDrawer(),
body:Container(
height: size.height,
child: Column(
children: <Widget>[
const SizedBox(
height: 10,
),
AnimatedOpacity(
duration: const Duration(milliseconds: 200),
opacity: closeTopContainer?0:1,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: size.width,
alignment: Alignment.topCenter,
height: closeTopContainer?0:categoryHeight,
child: categoriesScroller),
),
Expanded(
child: ListView.builder(
controller: controller,
itemCount: itemsData.length,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return itemsData[index];
})),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Add your onPressed code here!
},
child: const Icon(Icons.add),
backgroundColor: Color(0xFF6D4C41),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
),
);
}
}
void _navigateAndDisplaySelection(BuildContext context) async {
// Navigator.push returns a Future that completes after calling
// Navigator.pop on the Selection Screen.
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => SearchCustomerScreen()),
);
}
class CategoriesScroller extends StatelessWidget {
const CategoriesScroller();
#override
Widget build(BuildContext context) {
final double categoryHeight = MediaQuery.of(context).size.height * 0.35 - 50;
return SingleChildScrollView(
physics: BouncingScrollPhysics(),
// scrollDirection: Axis.horizontal,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 25, horizontal: 25),
child: FittedBox(
fit: BoxFit.fill,
alignment: Alignment.topCenter,
child: Row(
children: <Widget>[
Container(
width: 400,
margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
height: categoryHeight,
decoration: BoxDecoration(color: Color(0XFFc49864), borderRadius: BorderRadius.all(Radius.circular(20.0)),boxShadow: [
BoxShadow(color: Colors.black.withAlpha(100), blurRadius: 10.0),]),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
RoundInputField(
hintText: "Customer Name",
onChanged: (value) {},
),
RoundInputFieldNumber(
hintText: "Phone Number",
icon: Icons.phone,
onChanged: (value) {},
),
],
),
),
),
],
),
),
),
);
}
}
class bottombar extends StatelessWidget {
const bottombar();
#override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomAppBar(
child: Row(
children: [
IconButton(icon: Icon(Icons.menu), onPressed: () {}),
Spacer(),
IconButton(icon: Icon(Icons.search), onPressed: () {}),
IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
],
),
),
floatingActionButton:
FloatingActionButton(child: Icon(Icons.add), onPressed: () {}),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
}
The most straight forward way is imho:
embed the widget to be added with showWidgetA ? WidgetA() : Container();
in your button you toggle the value onPressed: () => showWidgetA = !showWidgetA (showWidgetA being bool)
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
I am building this flutter App. My problem is I canno fit all the widgets in one screen. and all the font sizes and icons seem to be different although they are meant to be the same. In ReusableCard, when the Container height and width properties are set to 200 and 250 respectively, the whole app resizes but they are not uniform as shown in the picture. Does anyone has a suggestion?
import 'results_page.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'icon_content_widget.dart';
import 'reusable_card.dart';
import 'bottom_button.dart';
import 'calculator_brain.dart';
import 'constants.dart';
enum GenderType {
male,
female,
}
class InputPage extends StatefulWidget {
#override
_InputPageState createState() => _InputPageState();
}
class _InputPageState extends State<InputPage> {
GenderType selectedGender;
int height = 180;
int weight = 60;
int age = 20;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('CALCULATE BMI'), centerTitle: true),
body: ListView(
scrollDirection: Axis.vertical,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
child: FittedBox(
child: Material(
color: Color(0xFF00053C),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
child: ReusableCard(
onPress: () {
setState(() {
selectedGender = GenderType.male;
});
},
colour: selectedGender == GenderType.male
? kActiveCardColor
: kInactiveCardColor,
cardChild:
IconContentWidget('MALE', FontAwesomeIcons.mars),
),
),
Container(
child: ReusableCard(
onPress: () {
setState(() {
selectedGender = GenderType.female;
});
},
colour: selectedGender == GenderType.female
? kActiveCardColor
: kInactiveCardColor,
cardChild: IconContentWidget(
'FEMALE', FontAwesomeIcons.venus),
),
),
],
),
),
),
),
),
Padding(
padding: const EdgeInsets.all(1.0),
child: Container(
child: FittedBox(
child: Material(
color: Color(0xFF00053C),
child: Row(
children: <Widget>[
Container(
child: ReusableCard(
colour: kActiveCardColor,
cardChild: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('HEIGHT', style: kLabelTextStyle),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: <Widget>[
Text(height.toString(),
style: kNumberTextStyle),
Text('cm', style: kLabelTextStyle),
],
),
SliderTheme(
data: SliderTheme.of(context).copyWith(
activeTrackColor: Colors.white,
inactiveTrackColor: Color(0xFF8D8E98),
thumbColor: Color(0xFFEB1555),
overlayColor: Color(0x29EB1555),
thumbShape: RoundSliderThumbShape(
enabledThumbRadius: 15.0),
overlayShape: RoundSliderOverlayShape(
overlayRadius: 30.0),
),
child: Slider(
value: height.toDouble(),
min: 120.0,
max: 220.0,
onChanged: (double newValue) {
setState(() {
height = newValue.round();
});
},
),
),
],
),
),
),
],
),
),
),
),
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
child: FittedBox(
child: Material(
color: Color(0xFF00053C),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
child: ReusableCard(
colour: kActiveCardColor,
cardChild: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'WEIGHT(Kg)',
style: kLabelTextStyle,
),
Text(
weight.toString(),
style: kNumberTextStyle,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RoundIconButton(
iconName: FontAwesomeIcons.minus,
onPressed: () {
setState(() {
weight--;
});
},
),
SizedBox(
width: 15.0,
),
RoundIconButton(
iconName: FontAwesomeIcons.plus,
onPressed: () {
setState(() {
weight++;
});
},
),
],
),
],
),
),
),
Container(
child: ReusableCard(
colour: kActiveCardColor,
cardChild: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'AGE',
style: kLabelTextStyle,
),
Text(age.toString(), style: kNumberTextStyle),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RoundIconButton(
iconName: FontAwesomeIcons.minus,
onPressed: () {
setState(() {
age--;
});
},
),
SizedBox(
width: 15.0,
),
RoundIconButton(
iconName: FontAwesomeIcons.plus,
onPressed: () {
setState(() {
age++;
});
},
)
],
),
],
),
),
),
],
),
),
),
),
),
BottomButton(
buttonTitle: 'CALCULATE',
onTap: () {
CalculatorBrain calc =
CalculatorBrain(height: height, weight: weight);
print(calc);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return ResultsPage(
bmiResult: calc.calculateBMI(),
interpretation: calc.getInterpretation(),
resultText: calc.getResult());
},
),
);
},
),
],
),
);
}
}
class RoundIconButton extends StatelessWidget {
final Function onPressed;
final IconData iconName;
RoundIconButton({#required this.iconName, this.onPressed});
#override
Widget build(BuildContext context) {
return RawMaterialButton(
shape: CircleBorder(),
fillColor: Color(0xFF4C4F5E),
constraints: BoxConstraints.tightFor(width: 56.0, height: 56.0),
elevation: 0.0,
onPressed: onPressed,
child: Icon(iconName),
);
}
}
class ReusableCard extends StatelessWidget {
ReusableCard({#required this.colour, this.cardChild, this.onPress});
final Color colour;
final Widget cardChild;
final Function onPress;
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPress,
child: Container(
height: 200,
width: 250,
child: cardChild,
margin: EdgeInsets.all(5.0),
decoration: BoxDecoration(
color: colour,
borderRadius: BorderRadius.circular(10.0),
),
),
);
}
}[![enter image description here][1]][1]