CheckBox ListTile in Flutter not working? - flutter

I'm building a ToDo App, and CheckboxListTile not working and I don't know what went wrong, can anyone help?
class mainTaskScreen extends StatefulWidget {
const mainTaskScreen({Key? key}) : super(key: key);
#override
State<mainTaskScreen> createState() => _mainTaskScreenState();
}
class _mainTaskScreenState extends State<mainTaskScreen> {
#override
Widget build(BuildContext context) {
bool _valueCheck = false;
return Scaffold(
backgroundColor: const Color(0XFF7FC8F8),
//------------------------------------------------------------------------------
// AddTask Button...
floatingActionButton: FloatingActionButton(
onPressed: (() {}),
backgroundColor: AppColor.mainColor,
child: const Icon(FontAwesomeIcons.plus),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding:
const EdgeInsets.only(top: 60, left: 30, right: 30, bottom: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//------------------------------------------------------------------------------
// Menu Button..
(ElevatedButton(
style: ElevatedButton.styleFrom(
primary: AppColor.accentColor,
onPrimary: AppColor.mainColor,
fixedSize: const Size(70, 70),
shape: const CircleBorder()),
onPressed: (() {}),
child: const Icon(FontAwesomeIcons.listUl, size: 30),
)),
const SizedBox(height: 10),
//------------------------------------------------------------------------------
// Title...
Text('Todoey', style: AppFonts.titleStyle),
//------------------------------------------------------------------------------
// Task's Num...
Text('12 Task', style: AppFonts.smallStyle),
],
),
),
//------------------------------------------------------------------------------
// Task's List...
Expanded(
child: Container(
padding: const EdgeInsets.only(left: 20),
width: double.infinity,
decoration: const BoxDecoration(
color: AppColor.accentColor,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(25),
topRight: Radius.circular(25),
),
),
child: ListView(
children: [
CheckboxListTile(
title: Text('Clean you room', style: taskText.smallStyle),
subtitle:
const Text('remove the trach + clean your cloths'),
activeColor: AppColor.accentColor,
checkColor: AppColor.mainColor,
value: _valueCheck,
selected: _valueCheck,
onChanged: ((value) {
setState(() {
_valueCheck = value!;
});
}),
),
],
),
),
),
],
),
);
}
}

Move the bool outside the build method
class _mainTaskScreenState extends State<mainTaskScreen> {
bool _valueCheck = false; //<-- here
#override
Widget build(BuildContext context) {
return Scaffold(
);
}
}

It looks like your _valueCheck variable is defined in the build method of the state. Try defining it as a class member of instead of _mainTaskScreenState a local variable instead.
As it is, the setState is likely kicking off another build, but the _valueCheck value is redefined as false when that build happens.

Related

Change TabbarView in Flutter When pressed button from another class and also need to make swipe-able

Hey I m new in flutter now m stuck with the tab bar I have four files (Class), the first one is the parent file and the other three files(Class) are the child.
Now I want to change tabbarview when I clicked the button from the child class.
I also shared my sample code please help me.
This is My Parent Class
class AddItemTab extends StatefulWidget {
const AddItemTab({Key? key}) : super(key: key);
#override
_AddItemTabState createState() => _AddItemTabState();
}
class _AddItemTabState extends State<AddItemTab> {
final List<Widget> _fragments = [
const ProductPurchase(),
const ProtectionProduct(),
const RoomProduct()
];
int _page = 0;
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
backgroundColor: MyColor.backgroundColor,
body: Padding(
padding: const EdgeInsets.only(
top: 50.0, right: 20.0, left: 20.0, bottom: 20.0),
child: Container(
child: Column(
children: [
Row(
children: [
Align(
alignment: Alignment.centerLeft,
child: IconButton(
padding: EdgeInsets.zero,
constraints: BoxConstraints(),
onPressed: () {
Navigator.of(context).pop();
},
icon: const Icon(Icons.arrow_back_ios),
),
),
Text("Back"),
],
),
SizedBox(
height: 15,
),
const Align(
alignment: Alignment.centerLeft,
child: Text(
'Add an item',
style: TextStyle(
color: Colors.black,
fontSize: 34,
fontFamily: 'Inter',
fontWeight: FontWeight.w700,
),
)),
const SizedBox(
height: 15,
),
Container(
height: 55,
width: double.infinity,
child: const TabBar(
indicator: BoxDecoration(
color: MyColor.buttonColor,
borderRadius: BorderRadius.all(
Radius.circular(5),
),
),
indicatorWeight: 5,
indicatorPadding: EdgeInsets.only(top:50),
// controller: _tabController,
labelColor: Colors.black,
tabs: [
Tab(
child: Text(
"Purchase",
textAlign: TextAlign.center,
),
),
Tab(
text: 'Protection',
),
Tab(
text: 'Room',
),
],
),
),
const SizedBox(height: 20),
Expanded(
child: TabBarView(
children: [
_fragments[0],
_fragments[1],
_fragments[2],
],
))
],
),
),
)),
);
}
}
This is My Child Class
class ProductPurchase extends StatefulWidget {
const ProductPurchase({Key? key}) : super(key: key);
#override
_ProductPurchaseState createState() => _ProductPurchaseState();
}
class _ProductPurchaseState extends State<ProductPurchase> {
final List<Widget> _fragments = [
const ProtectionProduct(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: MyColor.backgroundColor,
body: Stack(
children: [
Padding(
padding: EdgeInsets.only(bottom: 50),
child: Align(
alignment: Alignment.bottomCenter,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
elevation: 5,
),
onPressed: () {
// Navigator.of(context).push(MaterialPageRoute(
// builder: (context) => ProductView()));
// _fragments[0];
},
child: Ink(
decoration: BoxDecoration(
color: MyColor.buttonColor,
borderRadius: BorderRadius.circular(10)),
child: Container(
width: 250,
padding: const EdgeInsets.all(15),
constraints: const BoxConstraints(minWidth: 88.0),
child: const Text('Go To Next Tabbar View',
textAlign: TextAlign.center,`enter code here`
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
),
),
],
),
);
}
}
You need to use TabController for this , while you already have tab Bar and tab Bar view, you can do it like
class _AddItemTabState extends State<AddItemTab>
with SingleTickerProviderStateMixin {
final List<Widget> _fragments = [
.....
];
late final TabController controller = TabController(length: 3, vsync: this);
#override
Widget build(BuildContext context) {
........
child: TabBar(
controller: controller,
......
Expanded(
child: TabBarView(
controller: controller,
And to move n index, here 2
onPressed: () {
controller.animateTo(2);
},
To call from different widget using callback method
class ProductPurchase extends StatefulWidget {
final VoidCallback callback;
const ProductPurchase({Key? key, required this.callback}) : super(key: key);
.....
onPressed: (){
widget.callback();
},
Once you used this widget, provide
ProductPurchase(callback: (){
controller.animateTo(2);
},);
class ProductPurchase extends StatefulWidget {
final VoidCallback callback;
const ProductPurchase({Key? key, required this.callback}) : super(key: key);
#override
_ProductPurchaseState createState() => _ProductPurchaseState();
}
class _ProductPurchaseState extends State<ProductPurchase> {
#override
Widget build(BuildContext context) {
return Scaffold(
// backgroundColor: MyColor.backgroundColor,
body: Stack(
children: [
Padding(
padding: EdgeInsets.only(bottom: 50),
child: Align(
alignment: Alignment.bottomCenter,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
elevation: 5,
),
onPressed: () {
widget.callback(); //this
},
child: Ink(
decoration: BoxDecoration(
color: MyColor.buttonColor,
borderRadius: BorderRadius.circular(10)),
child: Container(
width: 250,
padding: const EdgeInsets.all(15),
constraints: const BoxConstraints(minWidth: 88.0),
child: const Text('Go To Next Tabbar View',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
),
),
],
),
);
}
}
And fragments
late final List<Widget> _fragments = [
ProductPurchase(
callback: () {
controller.animateTo(3);
},
),
Container(color: Colors.cyanAccent, child: Stack(children: [Text("fsA")])),
Text("2A")
];
More about TabBar

Flutter: A list of generated TextFields deletes item at the final index regardless of the index passed

Assuming I have created 10 fields and use the delete button at index 2, the fields reduce to 9 but the item in index 10 is deleted instead of deleting 2 and moving up the others. I have written some minimal reproduction of the code
Here is the sample code.
import 'package:flutter/material.dart';
void main() {
runApp(const EditFields());
}
class EditFields extends StatefulWidget {
const EditFields({Key? key}) : super(key: key);
#override
State<EditFields> createState() => _EditFieldsState();
}
class _EditFieldsState extends State<EditFields> {
List<String> openRoles = [];
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'ShrinkWrap vs Slivers',
home: Scaffold(
appBar: AppBar(
title: const Text("ShrinkWrap"),
),
body: Column(
children: [
...List.generate(
openRoles.length,
(i) {
return Row(
children: [
SizedBox(
width: 300,
child: TextFormField(
maxLines: 1,
key: Key('rolefield$i'),
//..decoration
onChanged: (value) {
setState(() {
openRoles[i] = value!;
});
},
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: InkWell(
onTap: () {
openRoles.removeAt(i);
setState(() {});
},
child: const Icon(
Icons.delete,
color: Colors.red,
size: 24,
),
),
),
],
);
},
),
ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 0,
primary: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
side: const BorderSide(color: Colors.blue))),
child: Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Padding(
padding: EdgeInsets.all(4.0),
child: Icon(
Icons.add_rounded,
size: 25,
color: Colors.blue,
),
),
Text('ADD', style: TextStyle(color: Colors.blue)),
],
),
onPressed: () {
openRoles.add("Text");
setState(() {});
}),
],
),
),
);
}
}
The issue is with using key, once a single item remove key changes by from
List.generate(
openRoles.length,
(i) {
If we do use map instead of list, removing n item, Data will for n> items. We can use TextEditingController in this case to work properly
class EditFields extends StatefulWidget {
const EditFields({Key? key}) : super(key: key);
#override
State<EditFields> createState() => _EditFieldsState();
}
class _EditFieldsState extends State<EditFields> {
List<TextEditingController> controllers = [];
int counterX = 0;
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'ShrinkWrap vs Slivers',
home: Scaffold(
appBar: AppBar(
title: const Text("ShrinkWrap"),
),
body: Column(
children: [
for (final c in controllers) rowB(c),
ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 0,
primary: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
side: const BorderSide(color: Colors.blue))),
child: Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Padding(
padding: EdgeInsets.all(4.0),
child: Icon(
Icons.add_rounded,
size: 25,
color: Colors.blue,
),
),
Text('ADD', style: TextStyle(color: Colors.blue)),
],
),
onPressed: () {
controllers.add(TextEditingController());
setState(() {});
}),
],
),
),
);
}
Row rowB(TextEditingController c) {
return Row(
children: [
SizedBox(
width: 300,
child: TextFormField(
maxLines: 1,
controller: c,
//..decoration
onChanged: (value) {
setState(() {});
},
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: InkWell(
onTap: () {
controllers.remove(c);
setState(() {});
},
child: const Icon(
Icons.delete,
color: Colors.red,
size: 24,
),
),
),
],
);
}
}

Flutter -Widget Text, not updating when value change even with SetState

I have created a container. His child is a text.
When I tap on the container/text, it display a modal and a Picker.
Then, the user can select a value. Press the confirm button and my text widget should change to display the value selected by the user.
But in my case, it is not updating the value of the text widget. I have used that in the past and it was working very well. But here it is not and I do not see why. I am on this since 8:00. A little help would be appreciated. Many thanks.
int valuePickerUnitSelected =0;
String unitCount = '';
int unitCountInt;
String goal = "";
List <String> unitForHabits = ['Count', 'Minute(s)','Hour(s)','Gramme(s)', 'Pound(s)'];
class AddingHabitDetails extends StatefulWidget {
const AddingHabitDetails({Key key}) : super(key: key);
#override
_AddingHabitDetailsState createState() => _AddingHabitDetailsState();
}
class _AddingHabitDetailsState extends State<AddingHabitDetails> {
BuildContext get ctx => null;
#override
Widget build(BuildContext context) {
return Scaffold(
//drawer: new MyMenu(), //TODO a remettre
appBar: new AppBar(
title: new Text('Habits'),
),
body: Column(
children: [
titleZone('Name'),
textFieldHabits('Habit name', context),
titleZone('Goals'),
FlatButton(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (unitCount.length < 2 )...[
Container(
width: 65,
decoration: BoxDecoration(
border: Border.all(color: Colors.blue,
),
color: Colors.blue,
borderRadius: BorderRadius.all(Radius.circular(20))),
child:
Center(child: Text(
'Time', style: TextStyle(color: Colors.black,))))
]
else
...[
Container(
width: 65,
decoration: BoxDecoration(
border: Border.all(color: Colors.blue,),
color: Colors.blue,
borderRadius: BorderRadius.all(
Radius.circular(20))),
child: Center(
child: Text(
unitCount, style: TextStyle(color: Colors.black,))))
],
],
),
onPressed: () {
setState(() {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return ShowPickerUnite(unitForHabits);
});
},
);
},
),
//ChipGoalV3(ctx),// ChipGoal(),
textFieldHabits('Goals', context),
titleZone('Frequency'),
textFieldHabits('Frequency', context),
titleZone('Time Range'),
titleZone('Reminder'),
titleZone('Habits Term'),
],
),
);
}
}
//########################################################################
class ShowPickerUnite extends StatefulWidget {
List<String> myListUnit;
ShowPickerUnite(this.myListUnit, {Key key}) : super(key: key);
#override
_ShowPickerUniteState createState() => _ShowPickerUniteState(
myListUnit);
}
class _ShowPickerUniteState extends State<ShowPickerUnite> {
List <String> myListUnit;
_ShowPickerUniteState(this.myListUnit);
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
decoration: BoxDecoration(
color: Color(0xffffffff),
border: Border(
bottom: BorderSide(
color: Color(0xffffffff),
width: 0.0,
),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CupertinoButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 5.0,
),
),
DefaultTextStyle(
style: TextStyle(
fontSize: 16.0,
color: Colors.black,
fontWeight: FontWeight.bold),
child: Text('Select what you want'),
),
// Text('Energy Needed', style: TextStyle(fontSize: 12.0, color: Colors.black),
// ),
CupertinoButton(
child: Text('Confirm'),
onPressed: () {
setState(() {
unitCount = unitForHabits[valuePickerUnitSelected];
print(unitCount);
});
Navigator.of(context).pop();
},
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 5.0,
),
),
],
),
),
Container(
//width: 360,
height: 200,
decoration:BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(15.0)),
),
child: CupertinoPicker(
backgroundColor: Colors.white ,
useMagnifier: true,
magnification: 1.3,
scrollController: FixedExtentScrollController(initialItem: 0),
itemExtent: 25,
children: [
for (String name in myListUnit)
Center(
child:Text(name)),
],
onSelectedItemChanged: (value) {
setState(() {
valuePickerUnitSelected = value;
// taskEnergy = myListEnergy[valuePickerEnergySelected];
// taskNewValue ['task_Energy'] = taskEnergy;
});
}))
]);
}
}
Widget inputNameHabit (){
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text ('Name Habits',style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold),),
);
}
Widget titleZone (String _titleName){
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Text ( _titleName,
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold),),
],
),
);
}
Widget textFieldHabits (String item,context){
return TextField(
decoration: InputDecoration(
hintText: item,
filled: true,
fillColor: Colors.grey[300],
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(50)
),
),
onTap: (){
Navigator.push(context,
MaterialPageRoute(
builder: (context) => HabitGoalUnitSelection(), //TODO MODIFIER route selon source
),
);
},);
}
Wait for the dialog to finish and then call setState to update the UI.
Modify this way
onPressed: () async {
await showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return ShowPickerUnite(unitForHabits);
});
setState(() {});

How to make a 3 dot pop up menu in app-bar in flutter. Image link is below

enter image description hereAs per image I want popup in app-bar in flutter
Try the below code and you will store the SVG image in image directory
actions[
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 5),
child: GestureDetector(
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(width: 2, color: Colors.blue)),
child: SvgPicture.asset(
"images/ic_more.svg",
height: 30,
color: Colors.white,
),
),
onTapDown: (details) {
_showPopUpMenu(details.globalPosition);
})
)
]
popUpMenu:
_showPopUpMenu(Offset offset) async {
final screenSize = MediaQuery.of(context).size;
double left = offset.dx;
double top = offset.dy;
double right = screenSize.width - offset.dx;
double bottom = screenSize.height - offset.dy;
await showMenu<MenuItemType>(
context: context,
position: RelativeRect.fromLTRB(left, top, right, bottom),
items: MenuItemType.values
.map((MenuItemType menuItemType) =>
PopupMenuItem<MenuItemType>(
value: menuItemType,
child: Text(getMenuItemString(menuItemType)),
))
.toList(),
).then((MenuItemType item) {
if (item == MenuItemType.EDIT) {
// here set your route
}
});
}
And your enum data for popup menu
import 'package:flutter/foundation.dart';
enum MenuItemType {
EDIT,
DUPLICATE
}
getMenuItemString(MenuItemType menuItemType) {
switch (menuItemType) {
case MenuItemType.EDIT:
return "Edit";
case MenuItemType.DUPLICATE:
return "Duplicate";
}
}
Please refer to below code
Using custom_pop_up_menu: ^1.2.2
https://pub.dev/packages/custom_pop_up_menu
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<ChatModel> messages;
List<ItemModel> menuItems;
CustomPopupMenuController _controller = CustomPopupMenuController();
#override
void initState() {
menuItems = [
ItemModel('Chat', Icons.chat_bubble),
ItemModel('Add', Icons.group_add),
ItemModel('View', Icons.settings_overscan),
];
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('CustomPopupMenu'),
actions: <Widget>[
CustomPopupMenu(
child: Container(
child: Icon(
Icons.more_horiz,
color: Colors.white,
size: 24.0,
),
padding: EdgeInsets.symmetric(
horizontal: 30.0,
vertical: 20.0,
),
),
menuBuilder: () => ClipRRect(
borderRadius: BorderRadius.circular(5),
child: Container(
color: Colors.white,
child: IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: menuItems
.map(
(item) => GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: _controller.hideMenu,
child: Container(
height: 40,
padding: EdgeInsets.symmetric(horizontal: 20),
child: Row(
children: <Widget>[
Icon(
item.icon,
size: 15,
color: Colors.black,
),
Expanded(
child: Container(
margin: EdgeInsets.only(left: 10),
padding:
EdgeInsets.symmetric(vertical: 10),
child: Text(
item.title,
style: TextStyle(
color: Colors.black,
fontSize: 12,
),
),
),
),
],
),
),
),
)
.toList(),
),
),
),
),
pressType: PressType.singleClick,
verticalMargin: -10,
controller: _controller,
barrierColor: Colors.black54,
horizontalMargin: 0.0,
arrowColor: Colors.white,
showArrow: true,
),
],
),
body: Container(
child: Center(
child: Text(
"Pop up menu",
),
),
),
);
}
}
Solution Using PopupmenuButton
Widget popMenus({
List<Map<String, dynamic>> options,
BuildContext context,
}) {
return PopupMenuButton(
iconSize: 24.0,
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
icon: Icon(
Icons.more_horiz_rounded,
color: Colors.black,
size: 24.0,
),
offset: Offset(0, 10),
itemBuilder: (BuildContext bc) {
return options
.map(
(selectedOption) => PopupMenuItem(
height: 12.0,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
selectedOption['menu'] ?? "",
style: TextStyle(
fontSize: ScreenUtil().setSp(14.0),
fontWeight: FontWeight.w400,
fontStyle: FontStyle.normal,
color: Colors.blue,
),
),
(options.length == (options.indexOf(selectedOption) + 1))
? SizedBox(
width: 0.0,
height: 0.0,
)
: Padding(
padding: EdgeInsets.symmetric(
vertical: 8.0,
),
child: Divider(
color: Colors.grey,
height: ScreenUtil().setHeight(1.0),
),
),
],
),
value: selectedOption,
),
)
.toList();
},
onSelected: (value) async {},
);
}
class PopUpmenusScreen extends StatefulWidget {
const PopUpmenusScreen({Key key}) : super(key: key);
#override
_PopUpmenusScreenState createState() => _PopUpmenusScreenState();
}
class _PopUpmenusScreenState extends State<PopUpmenusScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Examples"),
actions: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0,),
child: popMenus(
context: context,
options: [
{
"menu": "option 1" ?? '',
"menu_id": 1,
},
{
"menu": "option 2" ?? "",
"menu_id": 2,
},
{
"menu": "option 3" ?? "",
"menu_id": 3,
},
{
"menu": "option 4" ?? "",
"menu_id": 4,
},
],
),
)
],
),
);
}
}
Solution 2:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Examples"),
actions: [
IconButton(
icon: Icon(
Icons.more_horiz,
color: Colors.black,
size: 20.0,
),
onPressed: () {},
)
],
),
);
}
You can do that easily using DropdownButton2 which is customizable Flutter's core DropdownButton.
It has customButton parameter which will replace the normal Button with Image, Icon or any widget you want. You can customize everything and design what you need by using many options described with the package. Also, you can change the position of the dropdown menu by using the offset parameter.
Here's an example of using DropdownButton2 as a Popup Menu with Icon:
class CustomButtonTest extends StatefulWidget {
const CustomButtonTest({Key? key}) : super(key: key);
#override
State<CustomButtonTest> createState() => _CustomButtonTestState();
}
class _CustomButtonTestState extends State<CustomButtonTest> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButtonHideUnderline(
child: DropdownButton2(
customButton: const Icon(
Icons.list,
size: 46,
color: Colors.red,
),
customItemsIndexes: const [3],
customItemsHeight: 8,
items: [
...MenuItems.firstItems.map(
(item) =>
DropdownMenuItem<MenuItem>(
value: item,
child: MenuItems.buildItem(item),
),
),
const DropdownMenuItem<Divider>(enabled: false, child: Divider()),
...MenuItems.secondItems.map(
(item) =>
DropdownMenuItem<MenuItem>(
value: item,
child: MenuItems.buildItem(item),
),
),
],
onChanged: (value) {
MenuItems.onChanged(context, value as MenuItem);
},
itemHeight: 48,
itemWidth: 160,
itemPadding: const EdgeInsets.only(left: 16, right: 16),
dropdownPadding: const EdgeInsets.symmetric(vertical: 6),
dropdownDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: Colors.redAccent,
),
dropdownElevation: 8,
offset: const Offset(0, 8),
),
),
),
);
}
}
class MenuItem {
final String text;
final IconData icon;
const MenuItem({
required this.text,
required this.icon,
});
}
class MenuItems {
static const List<MenuItem> firstItems = [home, share, settings];
static const List<MenuItem> secondItems = [logout];
static const home = MenuItem(text: 'Home', icon: Icons.home);
static const share = MenuItem(text: 'Share', icon: Icons.share);
static const settings = MenuItem(text: 'Settings', icon: Icons.settings);
static const logout = MenuItem(text: 'Log Out', icon: Icons.logout);
static Widget buildItem(MenuItem item) {
return Row(
children: [
Icon(
item.icon,
color: Colors.white,
size: 22
),
const SizedBox(
width: 10,
),
Text(
item.text,
style: const TextStyle(
color: Colors.white,
),
),
],
);
}
static onChanged(BuildContext context, MenuItem item) {
switch (item) {
case MenuItems.home:
//Do something
break;
case MenuItems.settings:
//Do something
break;
case MenuItems.share:
//Do something
break;
case MenuItems.logout:
//Do something
break;
}
}
}

Stateful widget not updating, after being updated in setState, how to solve this?

I am new to Flutter. I am trying to build a Quiz App. Now, I am on the Quiz Screen, and then a quiz has multiple questions. I am showing the question title along with the answers, and when someone clicks on the answer, I am updating the QuestionView again with the new question data. These are stateful widgets, and when the result is fetched I am using setState to update the widget, and if I place a break point there I can see that the things are updated, but that is not rendered on the screen or the view is not changed, it has same title, answers and everything. I am using an optionTap method and you can find it in the comments below. I have mentioned where I am tapping the option and what is done below it.
Here's what I have done so far:
import 'package:flutter/material.dart';
import 'package:flutter_app/Constants/constants.dart';
import 'package:flutter_app/Models/question_model.dart';
import 'package:flutter_app/ViewModels/QuestionsVM.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
QuizQuestionViewModel questionViewModel = QuizQuestionViewModel();
QuizQuestionModel _questionModel;
Widget updateWidget;
class SQQuiz extends StatefulWidget {
final QuizQuestionModel quizQuestionModel;
final int quizId;
SQQuiz({Key key, #required this.quizQuestionModel, #required this.quizId})
: super(key: key);
#override
_SQQuizState createState() =>
_SQQuizState(quizQuestionModel: quizQuestionModel, quizId: quizId);
}
class _SQQuizState extends State<SQQuiz> {
final QuizQuestionModel quizQuestionModel;
final int quizId;
_SQQuizState(
{Key key, #required this.quizQuestionModel, #required this.quizId});
#override
Widget build(BuildContext context) {
_questionModel = quizQuestionModel;
updateWidget = QuestionView(
quizQuestionModel: _questionModel,
quizId: quizId,
);
return Scaffold(
appBar: AppBar(
leading: Container(
child: Row(
children: <Widget>[
IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back),
),
],
),
),
title: Padding(
padding: const EdgeInsets.symmetric(horizontal: 0),
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
_questionModel.questionDetail.quizName,
style: TextStyle(color: Constants.greyColor, fontSize: 12),
textAlign: TextAlign.left,
),
SizedBox(
width: 14,
),
CircularProgressIndicator(
value: 15,
strokeWidth: 2,
),
],
),
),
),
actions: <Widget>[
Container(
margin: const EdgeInsets.only(right: 10),
child: Center(
child: Container(
child: Text("SCORE ${_questionModel.score}"),
),
),
)
],
),
body: SafeArea(child: updateWidget),
);
}
}
class QuestionView extends StatefulWidget {
final QuizQuestionModel quizQuestionModel;
final int quizId;
QuestionView(
{Key key, #required this.quizQuestionModel, #required this.quizId})
: super(key: key);
#override
_QuestionViewState createState() => _QuestionViewState(
quizQuestionModel: quizQuestionModel,
quizId: quizId,
);
}
class _QuestionViewState extends State<QuestionView> {
final QuizQuestionModel quizQuestionModel;
final int quizId;
_QuestionViewState({#required this.quizQuestionModel, #required this.quizId});
#override
Widget build(BuildContext context) {
QuestionDetail questionDetail = quizQuestionModel.questionDetail;
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
height: 10,
),
Text(
"Question ${quizQuestionModel.count}/${quizQuestionModel.totalCount}",
style: TextStyle(fontSize: 12),
),
SizedBox(
height: 5,
),
Image(
image: NetworkImage(
questionDetail.pic,
),
fit: BoxFit.cover,
),
Container(
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 50),
color: Constants.orangeColor,
child: Text(
questionDetail.title,
style: TextStyle(
color: Colors.white,
fontSize: 16,
),
textAlign: TextAlign.center,
),
),
ListView.builder(
itemBuilder: (context, index) {
Answers answers = questionDetail.answers[index];
return Card(
elevation: 5,
margin:
const EdgeInsets.symmetric(vertical: 10, horizontal: 0),
child: ListTile(
onTap: () { //This is where I am tapping the option
optionTap(
context: context,
sessionId: quizQuestionModel.sessionId,
quizId: quizId,
questionId: questionDetail.questionId,
answerId: answers.id,
hintUsed: false,
fiftyUsed: false,
).then((response) {
setState(() { //Here the updateWidget is updated, which you can see in the body, but it is not rendered
_questionModel = response;
updateWidget = new QuestionView(
quizQuestionModel: response,
quizId: quizId,
); // The new QuestionView with new details
});
});
},
contentPadding: const EdgeInsets.symmetric(vertical: 10),
title: Text(
answers.title,
textAlign: TextAlign.center,
),
),
);
},
itemCount: questionDetail.answers.length,
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
padding: const EdgeInsets.symmetric(horizontal: 50),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
onPressed: () {
print("50-50 Tapped");
},
child: Text(
"50 | 50\n ${quizQuestionModel.fiftyCoin} coins",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
),
),
),
Wrap(
spacing: 3,
children: <Widget>[
Icon(FontAwesomeIcons.coins),
Text("${quizQuestionModel.coins}"),
],
),
RaisedButton(
padding: const EdgeInsets.symmetric(horizontal: 50),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
onPressed: () {
print("Hint Tapped");
},
child: Text(
"HINT\n ${quizQuestionModel.hintUsed} coins",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
),
),
)
],
),
],
)
],
);
}
There are no errors at the moment, can anyone please help me with this? Thanks in advance.
No offence - but I think you have completely misunderstood the concept of state management in flutter.
If you have a stateful widget, the setState() method triggers the build() method again. So setState is a notifier to say: Hey there was an update to our variable, please build again.
Your Stateful Widget is doing that. BUT there are no new updates on variables from that widget, because your variables ARE OUTSIDE of the widget. They won't get updated for your StatefulWidget. Consider to rethink you architecture. For small Apps it is enough to pass the variables in a constructor.
Here are some links to get closer to the Flutter-State-Management-Concept:
https://flutter.dev/docs/get-started/codelab
https://flutter.dev/docs/development/data-and-backend/state-mgmt/options