Flutter child widget refreshing parent widget - how to not do this - flutter

When the class members of child class PartnerInviter are changed inside the child class, somehow it changes the state of the parent class as well which is PartnerConnect. isInviteOption: true, isInviteSent: false => Parent widget resets the flag to false, false. I thing build of PartnerConnect is getting called. How do I fix this?
Parent widget is:
class PartnerConnect extends StatefulWidget{
bool isInviter = true;
#override
State<StatefulWidget> createState() {
return PartnerConnectState();
}
}
class PartnerConnectState extends State<PartnerConnect>{
final _scaffoldKey = GlobalKey<ScaffoldState>();
double card_elevation = 1;
TextEditingController phoneNumber = TextEditingController();
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
key: _scaffoldKey,
body: widget.isInviter ? PartnerInviter(
isInviteOption: false,
isInviteSent: false,
scaffoldKey: _scaffoldKey,
) : PartnerInvitee(
isInvitationAccepted: true,
inviterNumber: '9********0',
scaffoldKey: _scaffoldKey),
appBar: AppBar(
title: Text('Partner Connect'),
backgroundColor: Colors.white,
elevation: 0.0,
),
backgroundColor: Colors.white,
),
);
}
}
Child widget is:
class PartnerInviter extends StatefulWidget{
bool isInviteOption = false;
bool isInviteSent = false;
GlobalKey<ScaffoldState> scaffoldKey;
PartnerInviter({this.isInviteOption, this.isInviteSent, this.scaffoldKey});
#override
State<StatefulWidget> createState() {
return _PartnerInviterState();
}
}
class _PartnerInviterState extends State<PartnerInviter> {
double card_elevation = 1;
TextEditingController phoneNumber = TextEditingController();
#override
Widget build(BuildContext context) {
return inviterConnectBody();
}
Widget inviterConnectBody(){
return Container(
margin: EdgeInsets.all(MediaQuery.of(context).size.width*0.1),
child: ListView(
children: <Widget>[
Visibility(
child: numberInputWidget(),
visible: widget.isInviteOption,
replacement: Container(
child: Visibility(
child: RequestReceivedWidget(phoneNum: phoneNumber.value.text),
visible: widget.isInviteSent,
replacement: Container(
child: RequestRevokeWidget(phoneNum: phoneNumber.value.text),
),
),
),
)
],
),
);
}
Widget RequestRevokeWidget({String phoneNum}){
return Card(
elevation: card_elevation,
color: Colors.deepPurple[50],
child: Container(
height: MediaQuery.of(context).size.height * 0.3,
child: ListView(
children: <Widget>[
ListTile(
title: Text('Partner connected'),
subtitle: Text('Registered number: ${phoneNum}'),
),
Center(
child: Container(
margin: EdgeInsets.only(left: MediaQuery.of(context).size.width * 0.04, right: MediaQuery.of(context).size.width * 0.04),
child: RaisedButton(
color: Colors.deepPurple,
child: Padding(
padding: EdgeInsets.only(bottom: 5),
child: Text('Revoke access', style: TextStyle(color: Colors.white),),),
onPressed: (){
setState(() {
widget.isInviteOption = true;
SnackBar snackBar = SnackBar(content: Text('Partness access successfully revoked'),);
widget.scaffoldKey.currentState.showSnackBar(snackBar);
});
},
),
)),
],
),
),);
}
Widget RequestReceivedWidget({String phoneNum}){
return Card(
elevation: card_elevation,
color: Colors.deepPurple[50],
child: Container(
height: MediaQuery.of(context).size.height * 0.3,
child: ListTile(
title: Text('Waiting for partner to accept invite'),
subtitle: Text('Registered number: ${phoneNum}'),
),
),)
;
}
Widget numberInputWidget(){
final buttonMargin = MediaQuery.of(context).size.width * 0.038;
return Card(
elevation: card_elevation,
color: Colors.deepPurple[50],
child: Container(
height: MediaQuery.of(context).size.height * 0.3,
child: ListView(
children: <Widget>[
ListTile(
title: Text('Partner'),
subtitle: Text('Enter the phone number'),
),
Center(
child: Container(
margin: EdgeInsets.only(left: MediaQuery.of(context).size.width * 0.04, right: MediaQuery.of(context).size.width * 0.04),
child: TextField(
controller: phoneNumber,
keyboardType: TextInputType.number,
enabled: true,
maxLength: 10,
maxLengthEnforced: true,
decoration: InputDecoration(
prefixText: '+91-',
contentPadding: EdgeInsets.only(left: 5.0, bottom: 5.0),
),
),
)),
Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom)),
Container(
margin: EdgeInsets.only(left: buttonMargin, right: buttonMargin),
child: RaisedButton(
color: Colors.deepPurple,
elevation: 0,
padding: EdgeInsets.only(bottom: 5.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
child: Text(
"Confirm & Proceed",
style: TextStyle(
color: Colors.white,
fontFamily: "Nunito",
fontWeight: FontWeight.bold),
),
onPressed: () async {
RegExp regExp = new RegExp(r'(^[0-9]*$)');
if (phoneNumber.text.isEmpty) {
widget.scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text("Please enter the mobile number")));
} else if (!regExp.hasMatch(phoneNumber.text) || phoneNumber.text.length < 10) {
widget.scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text("Please enter valid mobile number")));
} else {
setState(() {
widget.isInviteOption = false;
widget.isInviteSent = true;
});
}
},
),
),
],
),
),)
;
}
}

Related

setState updating inside StatefulBuilder but not updating when using a method outside

I am having a showMyModalBottomSheet that calls showModalBottomSheet which returns StatefulBuilder that has some widgets. The problem i am having is that if i setState it just works fine but if i setState in a method that i have called it does not work.
Below is my showMyModalBottomSheet method
showMyModalBottomSheet() {
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(25))),
builder: (context) {
return StatefulBuilder(builder: (context, setState) {
return Container(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom),
child: SingleChildScrollView(
child: Container(
width: double.infinity,
child: Column(children: [
Container(
width: double.infinity,
margin: const EdgeInsets.only(
left: 10, right: 10, top: 20, bottom: 20),
child: Text(
_titleText,
textAlign: TextAlign.center,
style:
TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
),
Container(
width: double.infinity,
margin: const EdgeInsets.only(
left: 20, right: 20, top: 10, bottom: 10),
child: TextFormField(
key: _titleFormKey,
decoration: InputDecoration(labelText: "Enter Title"),
controller: _titleController,
validator: (title) {
if (title!.isEmpty) {
return "Please enter title";
} else {
return null;
}
},
),
),
Container(
child: ElevatedButton(
onPressed: () {
if (_titleFormKey.currentState!.validate()) {
// updating title
_titleText = _titleController.text.trim().toString();
}
},
child: Text("Update Title"),
),
)
]),
),)
);
});
});
}
When i am updating my _titleText using below way it just works fine
onPressed: () {
if (_titleFormKey.currentState!.validate()) {
_titleText = _titleController.text.trim().toString();
}
},
But when i am using my method updateTitle like below it does not update
onPressed: () {
if (_titleFormKey.currentState!.validate()) {
updateTitle(_titleController.text.trim().toString());
}
},
And below is my updateTitle method
updateTitle(String title){
setState(() {
_titleText = title;
});
}
Below is my entire code
import 'package:flutter/material.dart';
class MyPage extends StatefulWidget {
const MyPage({Key? key}) : super(key: key);
#override
State<MyPage> createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> {
String _titleText = "Test Title";
final _titleFormKey = GlobalKey<FormFieldState>();
TextEditingController _titleController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("My Page"),
),
body: Center(
child: ElevatedButton(
onPressed: () {
showMyModalBottomSheet();
},
child: Text("Show Bottom Sheet"),
),
),
);
}
showMyModalBottomSheet() {
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(25))),
builder: (context) {
return StatefulBuilder(builder: (context, setState) {
return Container(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom),
child: SingleChildScrollView(
child: Container(
width: double.infinity,
child: Column(children: [
Container(
width: double.infinity,
margin: const EdgeInsets.only(
left: 10, right: 10, top: 20, bottom: 20),
child: Text(
_titleText,
textAlign: TextAlign.center,
style:
TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
),
Container(
width: double.infinity,
margin: const EdgeInsets.only(
left: 20, right: 20, top: 10, bottom: 10),
child: TextFormField(
key: _titleFormKey,
decoration: InputDecoration(labelText: "Enter Title"),
controller: _titleController,
validator: (title) {
if (title!.isEmpty) {
return "Please enter title";
} else {
return null;
}
},
),
),
Container(
child: ElevatedButton(
onPressed: () {
if (_titleFormKey.currentState!.validate()) {
updateTitle(_titleController.text.trim().toString());
}
},
child: Text("Update Title"),
),
)
]),
),)
);
});
});
}
updateTitle(String title){
setState(() {
_titleText = title;
});
}
}
The problem is that its not updating text whenever i setState using updateTitle method.
updateTitle is using state class(_MyPageState) setState, that's why it is not updating. You can pass setState of StatefulBuilder while StatefulBuilder's setState is out of scope.
updateTitle(
_titleController.text.trim().toString(),
setState);
And
updateTitle(String title, setState) {
setState(() {
_titleText = title;
});
}

How to make Flutter GridView change colors when tapped

I have asked this question previously but I am not receiving much help. I've created a GridView using GridView.count; however, I cannot get an indiviual container to change colors. The entire row changes if I click on any container within the row. I want to be able to change an individual container's color when it is tapped on, as well as have check mark appear on the top right corner of the container when selected.
(1) My Layout
(2) An Example of what I would like to happen
I'm very new to Flutter, so my code is not very optimal. I've tried making a list model as well but I have not had any luck with that. I'm attaching a portion of my code to show what I've done so far. Any help would be great :)
Widget build(BuildContext) {
double _height = MediaQuery.of(context).size.height;
final data = ModalRoute.of(context)!.settings;
String retrieveString;
if (data.arguments == null) {
retrieveString = "empty";
} else {
retrieveString = data.arguments as String;
}
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: const Color(0xff31708c),
body: Padding(
padding: EdgeInsets.only(
left: 30,
right: 30,
top: _height * 0.2),
child: Column(
children: <Widget>[
Text('Hi $retrieveString! What all would you like to focus on?',
style: GoogleFonts.montserrat(
color: Colors.white70,
fontSize: 19,
fontWeight: FontWeight.w600
),
textAlign: TextAlign.center,),
const SizedBox(height: 9),
Text("You can pick all that apply:",
style: GoogleFonts.montserrat(
color: Colors.white70,
fontSize: 14.5,
fontWeight: FontWeight.w600
),),
const SizedBox(height: 9,),
Column(children: [
GridView.count(
primary: true,
shrinkWrap: true,
padding: const EdgeInsets.all(10),
childAspectRatio: 1.15,
crossAxisCount: 2,
crossAxisSpacing: 25,
mainAxisSpacing: 25,
children: <Widget>[
GestureDetector(
onTap: () {
setState(() {
_ContainerColor = _ContainerColor == Colors.white
? Color(0xffa1d0e6)
: Colors.white;
});
},
child: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: const Color.fromARGB(255, 20, 83, 106),
width: 2.5),
color: _ContainerColor
),
child: Column(
children: [
const Align(alignment: Alignment.topCenter,
child: Icon(MyFlutterApp.relationships,
color: Color(0xff31708c),
size: 45,),
),
const SizedBox(height: 4,),
Text('Maintaining healthy relationships',
style: GoogleFonts.montserrat(
fontSize: 14,
fontWeight: FontWeight.w500,
color: const Color(0xff31708c)
),
textAlign: TextAlign.center,)
],
),
),
),
From my understanding, you have to do allow users to have multi-select, because of the line
You can pick all that apply:
So here is a custom stateful widget that helps you to do multi-select, you can have your own widget child inside the gridview.
class CustomPage extends StatefulWidget {
const CustomPage({Key? key}) : super(key: key);
#override
State<CustomPage> createState() => _CustomPageState();
}
class _CustomPageState extends State<CustomPage> {
String retrieveString = "";
List selectedIndex = [];
List dataItems = ['India', 'USA', 'Germany'];
#override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
final data = ModalRoute.of(context)!.settings;
if (data.arguments == null) {
retrieveString = "empty";
} else {
retrieveString = data.arguments as String;
}
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: const Color(0xff31708c),
body: Padding(
padding: EdgeInsets.only(left: 30, right: 30, top: height * 0.2),
child: Column(children: <Widget>[
Text('Hi $retrieveString! What all would you like to focus on?'),
const SizedBox(height: 10),
const Text("You can pick all that apply:"),
const SizedBox(height: 10,),
Expanded(
child: GridView.builder(
scrollDirection: Axis.vertical,
primary: true,
shrinkWrap: true,
padding: const EdgeInsets.all(10),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
childAspectRatio: 1.15,
crossAxisCount: 2,
crossAxisSpacing: 25,
mainAxisSpacing: 25),
itemCount: dataItems.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
setState(() {
if (selectedIndex.contains(index)) {
selectedIndex.remove(index);
} else {
selectedIndex.add(index);
}
});
},
child: Stack(
alignment: Alignment.topRight,
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
border: Border.all(
color:
const Color.fromARGB(255, 20, 83, 106),
width: 2.5),
color: selectedIndex.contains(index)
? const Color(0xffa1d0e6)
: Colors.white),
child: Center(
child: Text(dataItems[index]),
),
),
selectedIndex.contains(index)
? Container(
padding: const EdgeInsets.all(10),
child: const CircleAvatar(
child: Icon(Icons.check_outlined),
),
)
: Container()
],
),
);
},
),
)
])));
}
}
Hope it resolves your issue.
I've created your app as a test version. All you need to do is inject your widget in the //put your widget here!!!!! section. Also for testing this right now as a demo, you can paste the code on dartpad and select "New" -> "Flutter" -> Paste Code: https://dartpad.dev
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowtappedModeBanner: false,
home: Scaffold(
body: Center(
child: CustomCheckboxGrid(),
),
),
);
}
}
class CustomCheckboxGrid extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _CustomCheckboxGridState();
}
}
class _CustomCheckboxGridState extends State<CustomCheckboxGrid> {
int tapped_index = 0;
List card_names = [
'Maintaining healthy relationships',
'Being happier and more content in life',
'Work life balance',
'Personal Growth',
'Stress',
'Mental health',
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: GridView.builder(
padding: const EdgeInsets.all(16),
itemCount: card_names.length,
itemBuilder: (BuildContext context, int index) {
return buildCard(index);
},
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
),
);
}
Widget buildCard(int index) {
bool tapped = index == tapped_index;
String current_name = card_names[index];
return GestureDetector(
onTap: () {
setState(() {
print("Tapped index: ${index}");
tapped_index = index;
});
},
child: Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(14),
child:
//put your widget here!!!!!
//-----------------------------------
Card(
color: tapped ? Colors.orange : Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
child: Container(
child: Center(child: Text(current_name)),
),
),
//-----------------------------------
),
Positioned(
top: 14,
right: 14,
child: Offstage(
offstage: !tapped,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(width: 2),
shape: BoxShape.circle),
child: Icon(
Icons.check,
color: Colors.green,
),
),
),
),
],
),
);
}
}

How to reduce the white space beside the drawer icon in Flutter?

In my flutter project, I have set one custom drawer.
Here's code for custom drawer-
class AppDrawer extends StatelessWidget {
#override
Widget build(BuildContext context) {
double defaultScreenWidth = 400.0;
double defaultScreenHeight = 810.0;
ScreenUtil.instance = ScreenUtil(
width: defaultScreenWidth,
height: defaultScreenHeight,
allowFontScaling: true,
)..init(context);
return SizedBox(
width: MediaQuery.of(context).size.width * 0.70,
child: Drawer(
child: Container(
color: Colors.black87,
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
SizedBox(height: ScreenUtil.instance.setHeight(30),),
_createDrawerItem(
icon: Icons.keyboard_arrow_right,
text: 'English to Bangla',
onTap: () =>
Navigator.pushReplacementNamed(context, Routes.englishToBangla)),
Padding(
padding: EdgeInsets.only(left:ScreenUtil.instance.setWidth(20), right: ScreenUtil.instance.setWidth(20)),
child: Divider(
height: ScreenUtil.instance.setHeight(10),
color: Colors.grey,
),
),
],
),
),
),
);
}
Widget _createHeader() {
return DrawerHeader(
margin: EdgeInsets.zero,
padding: EdgeInsets.zero,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.fill,
image: AssetImage('path/to/header_background.png'))),
child: Stack(children: <Widget>[
Positioned(
bottom: 12.0,
left: 16.0,
child: Text("Flutter Step-by-Step",
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.w500))),
]));
}
Widget _createDrawerItem(
{IconData icon, String text, GestureTapCallback onTap}) {
return ListTile(
title: Padding(
padding: EdgeInsets.only(left: ScreenUtil.instance.setWidth(10)),
child: Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.teal
),
child: Icon(icon, color: Colors.white,)
),
Padding(
padding: EdgeInsets.only(left: ScreenUtil.instance.setWidth(10)),
child: Text(text, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: ScreenUtil.instance.setSp(14) ),),
)
],
),
),
onTap: onTap,
);
}
}
Here's code for the toolBar which is shown beside the drawer icon-
class SearchAppBar extends StatefulWidget implements PreferredSizeWidget {
final PatternCallback onPatternSelected;
SearchAppBar(this.onPatternSelected, {Key key})
: preferredSize = Size.fromHeight(90),
super(key: key);
#override
final Size preferredSize; // default is 56.0
#override
_SearchAppBarState createState() => _SearchAppBarState();
}
class _SearchAppBarState extends State<SearchAppBar> {
TextEditingController _searchTextController = TextEditingController();
#override
Widget build(BuildContext context) {
double defaultScreenWidth = 400.0;
double defaultScreenHeight = 810.0;
ScreenUtil.instance = ScreenUtil(
width: defaultScreenWidth,
height: defaultScreenHeight,
allowFontScaling: true,
)..init(context);
return Container(
color: Colors.white,
child: Row(
children: <Widget>[
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(3),
),
child: Theme(
data:
Theme.of(context).copyWith(primaryColor: Color(0xFFff9900)),
child: TextFormField(
autofocus: false,
style: TextStyle(fontSize: ScreenUtil.instance.setSp(18)),
keyboardType: TextInputType.text,
controller: _searchTextController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Search for any word you want',
hintStyle:
TextStyle(fontSize: ScreenUtil.instance.setSp(16)),
contentPadding: EdgeInsets.symmetric(
vertical: 14,
horizontal: 10),
),
onChanged: (String value) {
widget.onPatternSelected(value);
},
),
),
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(0),
),
child: InkWell(onTap: (){
if(_searchTextController.text.isNotEmpty) {
Navigator.of(context).push(MaterialPageRoute(builder: (context)=>WordDetailScreen(_searchTextController.text.toLowerCase())));
}
},
child: Icon(Icons.search, color: Colors.blue,))),
SizedBox(width: 15)
],
),
);
}
}
And then, in the class where I want to use this drawer, I have called inside Scaffold like below-
drawer: AppDrawer()
But the problem is this causing a white space beside the drawer icon like below image-
And I am having no idea from where this extra padding or margin is happening. So, I need a solution to reduce this extra white space beside the drawer icon.
You can use Transform.translate to move the search bar to the left:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: Builder(builder: (context) {
return IconButton(
icon: Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer(),
);
}),
title: Transform.translate(
offset: Offset(-30.0, 0.0),
child: Text('this is the title') // here you can put the search bar
),
),
drawer: Drawer(
),
);
}
Just add a property called "titleSpacing" in your AppBar Tag,
Sample
appBar: AppBar(
titleSpacing: 0, //Add this line to your code
title: Text(widget.title),
leading: Icon(Icons.android),
),

CustomScrollView object does not update with input from StatefulBuilder

I have a CustomScrollView that gets updated upon user input. The actual items in the ListView are in a SliverChildBuilderDelegate inside the CustomScrollView which is inside the body of the Scaffold object (see the code below). If a user adds an item in the form that is inside the StatefulBuilder which is inside a showDialog object, the item does not get added to the planets list which thus does not update the ListView. I think the problem is caused by the StatefulBuilder which I need to update my DropdownButton.
My code:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
void main() {
runApp(MaterialApp(
home: HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class Planet {
final String id;
final String name;
final String location;
final String distance;
final String gravity;
final String image;
const Planet({this.id, this.name, this.location, this.distance, this.gravity, this.image});
}
class Coin {
int id;
String name;
Coin(this.id, this.name);
static List<Coin> getCoins() {
return <Coin>[
Coin(1, 'coin1'),
Coin(2, 'coin2'),
Coin(3, 'coin3'),
Coin(4, 'coin4'),
Coin(5, 'coin5'),
];
}
}
class MenuItem {
String title;
String icon;
Color color;
Function func;
MenuItem(this.title, this.icon, this.color, this.func);
}
class _HomePageState extends State<HomePage> {
List<Coin> _coins = Coin.getCoins();
List<DropdownMenuItem<Coin>> _dropdownMenuItems;
Coin _selectedCoin;
#override
void initState() {
_dropdownMenuItems = buildDropdownMenuItems(_coins);
_selectedCoin = _dropdownMenuItems[0].value;
super.initState();
_menuItems = createMenuItems();
_selectedMenuItem = _menuItems.first;
}
MenuItem _selectedMenuItem;
List<MenuItem> _menuItems;
List<Widget> _menuOptionWidgets = [];
List<MenuItem> createMenuItems() {
final menuItems = [
new MenuItem("Dashboard", 'assets/images/dashboard.png', Colors.black, () => new Dashboard()),
new MenuItem("Cows", 'assets/images/cow.png', Colors.green, () => new Cows()),
];
return menuItems;
}
_onSelectItem(MenuItem menuItem) {
setState(() {
_selectedMenuItem = menuItem;
});
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
Navigator.of(context).pop(); // close side menu
}
List<DropdownMenuItem<Coin>> buildDropdownMenuItems(List coins) {
List<DropdownMenuItem<Coin>> items = List();
for (Coin coin in coins) {
items.add(
DropdownMenuItem(
value: coin,
child:
Text(
coin.name,
style: TextStyle(
fontSize: 18.0,
color: Colors.black87,
fontWeight: FontWeight.bold
),
),
),
);
}
return items;
}
onChangeDropdownItem(Coin selectedCoin, StateSetter setState) {
setState(() {
_selectedCoin = selectedCoin;
print('${_selectedCoin.name}');
});
}
final coinController = TextEditingController();
final amountController = TextEditingController();
final purposeController = TextEditingController();
#override
void dispose() {
// Clean up the controller when the widget is disposed.
coinController.dispose();
amountController.dispose();
purposeController.dispose();
super.dispose();
}
List<Planet> planets = [];
#override
Widget build(BuildContext context) {
_menuOptionWidgets = [];
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd kk:mm').format(now);
for (var menuItem in _menuItems) {
_menuOptionWidgets.add(new Container(
decoration: new BoxDecoration(
color: menuItem == _selectedMenuItem
? Colors.grey[200]
: Colors.white),
child: new ListTile(
leading: new Image.asset(menuItem.icon),
onTap: () => _onSelectItem(menuItem),
title: Text(
menuItem.title,
style: new TextStyle(
fontSize: 20.0,
color: menuItem.color,
fontWeight: menuItem == _selectedMenuItem
? FontWeight.bold
: FontWeight.w300),
))));
_menuOptionWidgets.add(
new SizedBox(
child: new Center(
child: new Container(
margin: new EdgeInsetsDirectional.only(start: 20.0, end: 20.0),
height: 0.3,
color: Colors.grey,
),
),
),
);
}
double screenHeight;
screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
title: Text('Dashboard'),
backgroundColor: Color.fromRGBO(53, 73, 94, 0.9),
elevation: 0.0,
// leading: Container(),
),
drawer: new Drawer(
child: new ListView(
children: <Widget>[
new Container(
child: new ListTile(
leading: new CircleAvatar(
backgroundColor: Colors.black,
radius: 40.0,
child: Text(
"L",style: TextStyle(
color: Colors.orange,
fontSize: 46.0),
),
),
title: Text("Welcome",style: TextStyle(fontSize: 46.0),)
),
margin: new EdgeInsetsDirectional.only(top: 20.0),
color: Colors.white,
constraints: BoxConstraints(maxHeight: 90.0, minHeight: 90.0)),
new SizedBox(
child: new Center(
child: new Container(
margin:
new EdgeInsetsDirectional.only(start: 10.0, end: 10.0),
height: 0.3,
color: Colors.black,
),
),
),
new Container(
color: Colors.white,
child: new Column(children: _menuOptionWidgets),
),
],
),
),
floatingActionButton: new Container(
width: 120.0,
height: 120.0,
padding: const EdgeInsets.only(bottom:40.0),
child: FloatingActionButton(
child: Icon(Icons.add,size: 50.0),
elevation: 0.0,
onPressed: () {
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Container(
margin: EdgeInsets.only(
top: screenHeight / 5,
bottom: screenHeight / 4
),
padding: EdgeInsets.only(left: 10, right: 10),
child: Card(
color: Color.fromRGBO(53, 73, 94, 0.9),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
elevation: 8,
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Align(
alignment: Alignment.topCenter,
child: Text(
"Create",
style: Style.headerTextStyle
),
),
Divider(
color: Colors.white
),
SizedBox(
height: 15,
),
DropdownButton(
value: _selectedCoin,
items: _dropdownMenuItems,
onChanged: (selectedCoin) {
setState(() {
_selectedCoin = selectedCoin;
print('${_selectedCoin.name}');
});
}, //onChangeDropdownItem(_selectedCoin, setState),
),
SizedBox(
height: 15,
),
TextFormField(
decoration: InputDecoration(
labelText: "Amount",
hasFloatingPlaceholder: true,
labelStyle: Style.commonTextStyle
),
controller: amountController,
),
SizedBox(
height: 20,
),
TextFormField(
decoration: InputDecoration(
labelText: "What is it for?",
hasFloatingPlaceholder: true,
labelStyle: Style.commonTextStyle
),
controller: purposeController,
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment
.spaceEvenly,
children: <Widget>[
Expanded(
child: Container(),
),
ButtonTheme(
minWidth: 150.0,
child: RaisedButton(
padding: EdgeInsets.all(8.0),
child: Text('Share',
style: TextStyle(
fontSize: 24,
color: Colors.black87,
fontWeight: FontWeight.bold
),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
18.0)
),
color: Colors.white,
splashColor: Colors.blueGrey,
onPressed: () {
setState(() {
planets.add(Planet(
id: '1',
// TODO need to adjust this
name: purposeController.text,
location: '€' + amountController.text,
distance: formattedDate,
gravity: 'test',
image: _setImage(), // TODO might have to pass _selectedCoin as parameter
)
);
});
Navigator.pop(context);
},
),
),
],
),
],
),
),
),
);
}
);
},
);
},
),
),
body: Column(
children: <Widget>[
new Expanded(
child: new Container(
color: Color.fromRGBO(53, 73, 94, 0.9),
child: new CustomScrollView(
scrollDirection: Axis.vertical,
slivers: <Widget>[
new SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 0.0),
sliver: new SliverFixedExtentList(
itemExtent: 152.0,
delegate: new SliverChildBuilderDelegate(
(context, index) => new PlanetRow(planets[index]),
childCount: planets.length,
),
),
),
],
),
),
),
],
),
);
}
}
The expected result is that the object from user input gets added to the planets list. The Sliver object then gets the updated planets list which shows the user input in a Planet Card. Any help will be greatly appreciated!

How to Customize DropDown in flutter?

In flutter i have tried to modify drop down like below
i have tried using overlay with container but overlay is taking positioned from entire page. how to give positioned from previous widget to overlay
```import 'package:flutter/material.dart';
List titles = ['a','b','c','d',];
class sample extends StatefulWidget {
#override
CountriesFieldState createState() => CountriesFieldState();
}
class CountriesFieldState extends State<sample> {
final FocusNode _focusNode = FocusNode();
OverlayEntry _overlayEntry;
final LayerLink _layerLink = LayerLink();
OverlayEntry _createOverlayEntry() {
RenderBox renderBox = context.findRenderObject();
var size = renderBox.size;
var offset = renderBox.localToGlobal(Offset.zero);
return OverlayEntry(
builder: (context) => Positioned(
child: Container(
height: 240,
width: 320,
child: Scaffold(
body: Container(
margin: EdgeInsets.only(top: 8),
//color: Colors.red,
child: Column(
children: <Widget>[
new Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new Container(
//width: (320/360)*screenWidth,
decoration: new BoxDecoration(
border: new Border.all(color: Colors.white),
color: Colors.white),
child: new ListTile(
//dense: true,
contentPadding: EdgeInsets.only(
bottom: 0, left: 15, top: 0),
onTap: () {
_overlayEntry.remove();
},
title: new Text(
titles[index],
textAlign: TextAlign.left,
style: new TextStyle(
fontSize: 15,
fontFamily: "IBM Plex Sans Medium",
fontWeight: FontWeight.w500,
color: const Color(0xFF999aab)),
),
),
);
},
itemCount: titles.length,
)),
],
),
),
),
),
));
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
new InkWell(
child: Align(
alignment: Alignment.center,
child: Container(
margin: EdgeInsets.only(top: 100),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
width: 1.0, color: Colors.lightBlue.shade900),
),
// color: Colors.red,
),
height: 50.0,
width: 300.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[Text("abc")],
),
),
),
onTap: () {
this._overlayEntry = this._createOverlayEntry();
Overlay.of(context).insert(this._overlayEntry);
})
],
),
);
}
}```
i have used overlay concept to achieve this.
Is there any other solution to achieve customized dropdown???
This will help to achive your goal.
List titles = ['a','b','c','d',];
class Sample extends StatefulWidget {
#override
CountriesFieldState createState() => CountriesFieldState();
}
class CountriesFieldState extends State<Sample> {
final FocusNode _focusNode = FocusNode();
OverlayEntry _overlayEntry;
GlobalObjectKey _globalObjectKey = GlobalObjectKey(ValueKey('a_key_that_different_from_any_other')); // ADD THIS LINE
final LayerLink _layerLink = LayerLink();
OverlayEntry _createOverlayEntry() {
RenderBox renderBox =_globalObjectKey.currentContext?.findRenderObject(); //EDIT THIS LINE
var size = renderBox.size;
var offset = renderBox.localToGlobal(Offset.zero);
return OverlayEntry(
builder: (context) => Positioned(
child: Container(
height: 240,
width: 320,
child: Scaffold(
body: Container(
margin: EdgeInsets.only(top: 8),
//color: Colors.red,
child: Column(
children: <Widget>[
new Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new Container(
//width: (320/360)*screenWidth,
decoration: new BoxDecoration(
border: new Border.all(color: Colors.white),
color: Colors.white),
child: new ListTile(
//dense: true,
contentPadding: EdgeInsets.only(
bottom: 0, left: 15, top: 0),
onTap: () {
_overlayEntry.remove();
},
title: new Text(
titles[index],
textAlign: TextAlign.left,
style: new TextStyle(
fontSize: 15,
fontFamily: "IBM Plex Sans Medium",
fontWeight: FontWeight.w500,
color: const Color(0xFF999aab)),
),
),
);
},
itemCount: titles.length,
)),
],
),
),
),
),
));
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
new InkWell(
child: Align(
alignment: Alignment.center,
child: Container(
key: _globalObjectKey, // ADD THIS LINE
margin: EdgeInsets.only(top: 100),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
width: 1.0, color: Colors.lightBlue.shade900),
),
// color: Colors.red,
),
height: 50.0,
width: 300.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[Text("abc")],
),
),
),
onTap: () {
this._overlayEntry = this._createOverlayEntry();
Overlay.of(context).insert(this._overlayEntry);
})
],
),
);
}
}
use DropdownButton Widget where you can pass any Custom widget as Item
Container(
width: 200,
child: DropdownButton(
isExpanded: true,
hint: Text('Select Working Time'),
value: selectedVal,
items: List.generate(
titles.length, (i) {
return DropdownMenuItem(
value:titles[i],
child: Text(
titles[i],
style: Theme.of(context)
.primaryTextTheme
.caption,
));
}),
onChanged: (c) {
selectedVal = c.toString().toLowerCase();
setState(() {});
}),
)