PopupMenuButton not able to change icon when clicked - flutter

I'm using the PopupMenuButton in flutter for a web based project and trying to change the popupmenubutton icon when it's clicked. So in its initial state it would show Icons.menu and when opened, it could would Icons.close and once clicked again revert back to Icons.menu.
I have tried onSelected which does not get called at all when clicked in an attempt to change the icon.
I have used an icon or a child IconButton per the docs and used onPressed to setState however that doesn't work either.
Currently the elevated button when clicked, does not show the dropdown menu, nor does it update the icon.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool menuClicked = true;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
PointerInterceptor(
intercepting: true,
child: PopupMenuButton<String>(
offset: const Offset(10.0, 50.0),
color: Colors.black,
child: ElevatedButton(
onPressed: () {
setState(() {
menuClicked = !menuClicked;
});
},
child: Icon((menuClicked = true)
? Icons.menu
: Icons.close),),
itemBuilder: (BuildContext context) =>
<PopupMenuEntry<String>>[
PopupMenuItem(
value: "close",
child: ListTile(
leading: Icon(Icons.close, color: Colors.white),
title: Text('Close',
style: TextStyle(color: Colors.white)),
onTap: () {
Navigator.pop(context);
}),
),
],
),
],
),
),
body: Center(
child: Text('test'),
),
);
}
}

Equal sign will be ==
Icon((menuClicked == true) ? Icons.menu : Icons.close),
or you can do
Icon(menuClicked ? Icons.menu : Icons.close),
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool menuClicked = false;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
GestureDetector(
behavior: HitTestBehavior.translucent,
onPanDown: (details) {
setState(() {
menuClicked = true;
});
},
child: PopupMenuButton<String>(
offset: const Offset(10.0, 50.0),
color: Colors.black,
onSelected: (value) {
setState(() {
menuClicked = false;
});
},
padding: EdgeInsets.zero,
onCanceled: () {
setState(() {
menuClicked = false;
});
},
child: Icon(menuClicked ? Icons.close : Icons.menu),
itemBuilder: (BuildContext context) => [
PopupMenuItem(
value: "close",
child: ListTile(
leading: Icon(Icons.close, color: Colors.white),
title: Text(
'Close',
style: TextStyle(color: Colors.white),
),
onTap: () {
Navigator.pop(context);
},
),
),
],
),
),
],
),
);
}
}

Related

flutter/dart Undefined name 'context'. Try correcting the name to one that is defined, or defining the name

I have done IconButton in my main.dart appBar and I want to Navigate using this Icon to my second page named OneDice. When im trying to push it by using
Navigator.of(context).push(MaterialPageRoute(builder: (_) => OneDice(),),);
it doesnt work and I have no idea why.... Can u help me plis? The problem is with (context). Error name is in the topic. And here is mine code. Thanks for all!
import 'package:dicee/OneDice.dart';
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
return runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.green.shade300,
body: const DicePage(),
appBar: AppBar(
title: const Center(child: Text('Dicee')),
backgroundColor: Colors.purple,
elevation: 10.0,
actions: [
IconButton(
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (_) => OneDice(),),);
},
icon: const Icon(
Icons.indeterminate_check_box,
size: 40,
),
),
],
),
),
),
);
}
class DicePage extends StatefulWidget {
const DicePage({Key? key}) : super(key: key);
#override
State<DicePage> createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
int leftDiceNumber = 1;
int rightDiceNumber = 3;
void rollDice() {
setState(() {
leftDiceNumber = Random().nextInt(6) + 1;
rightDiceNumber = Random().nextInt(6) + 1;
});
}
#override
Widget build(BuildContext context) {
return Center(
child: Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
// when i will press dice it calls Widget build to rebuild
rollDice();
},
child: Image.asset('images/dice$leftDiceNumber.png'),
),
),
Expanded(
child: TextButton(
onPressed: () {
rollDice();
},
child: Image.asset('images/dice$rightDiceNumber.png'),
),
),
],
),
);
}
}
You can only access context in the build method. You could do it like this.
void main() {
return runApp(
MaterialApp(
home:MyWidget(),
),
);
}
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.green.shade300,
body: const DicePage(),
appBar: AppBar(
title: const Center(child: Text('Dicee')),
backgroundColor: Colors.purple,
elevation: 10.0,
actions: [
IconButton(
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (_) => OneDice(),),);
},
icon: const Icon(
Icons.indeterminate_check_box,
size: 40,
),
),
],
),
),
}
}
class DicePage extends StatefulWidget {
const DicePage({Key? key}) : super(key: key);
#override
State<DicePage> createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
int leftDiceNumber = 1;
int rightDiceNumber = 3;
void rollDice() {
setState(() {
leftDiceNumber = Random().nextInt(6) + 1;
rightDiceNumber = Random().nextInt(6) + 1;
});
}
#override
Widget build(BuildContext context) {
return Center(
child: Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
// when i will press dice it calls Widget build to rebuild
rollDice();
},
child: Image.asset('images/dice$leftDiceNumber.png'),
),
),
Expanded(
child: TextButton(
onPressed: () {
rollDice();
},
child: Image.asset('images/dice$rightDiceNumber.png'),
),
),
],
),
);
}
}
Just Use
Navigator.push(
context,
MaterialPageRoute(builder: (context) => OneDice()),);
And you can also use this code with GetX package
Get.to(() => OneDice());

How to use Flutter GetX Sidebar

How can I implement the design in the image (sidebar and navigation menu) in Flutter using GetX? similarly to Tabs on the web.
This is a example, maybe it can help you:
import 'package:flutter/material.dart';
import '../../routes/app_pages.dart';
import 'package:get/get.dart';
class SideBar extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Drawer(
child: Column(
children: <Widget>[
DrawerHeader(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: Icon(
Icons.person,
color: Colors.white,
size: 50.0,
),
),
Center(
child: Text(
"Vakup",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
],
),
decoration: BoxDecoration(
color: Colors.blueAccent,
),
),
ListTile(
leading: Icon(Icons.read_more),
title: Text('Leer datos'),
onTap: () {
if (Get.currentRoute == Routes.HOME) {
Get.back();
} else {
Get.toNamed(Routes.HOME);
}
},
),
ListTile(
leading: Icon(Icons.pets),
title: Text('Registrar animal'),
onTap: () {
if (Get.currentRoute == Routes.NEWANIMAL) {
Get.back();
} else {
Get.toNamed(Routes.NEWANIMAL);
}
},
),
ListTile(
leading: Icon(Icons.list_alt),
title: Text('Lista movimientos'),
onTap: () {
if (Get.currentRoute == Routes.MOVEMENTS) {
Get.back();
} else {
//Get.to
Get.toNamed(Routes.MOVEMENTS);
}
},
),
ListTile(
leading: Icon(Icons.list),
title: Text('Lista animales'),
onTap: () {
if (Get.currentRoute == Routes.LISTOFANIMALS) {
Get.back();
} else {
Get.toNamed(Routes.LISTOFANIMALS);
}
},
),
ListTile(
leading: Icon(Icons.edit),
title: Text('Grabar datos'),
onTap: () {
if (Get.currentRoute == Routes.GRABADO) {
Get.back();
} else {
Get.toNamed(Routes.GRABADO);
}
},
),
ListTile(
leading: Icon(Icons.bluetooth),
title: Text('Conexion BT'),
onTap: () {
if (Get.currentRoute == Routes.CONEXIONBT) {
Get.back();
} else {
Get.toNamed(Routes.CONEXIONBT);
}
},
),
ListTile(
leading: Icon(Icons.picture_as_pdf),
title: Text('Exportar Datos'),
onTap: () {
if (Get.currentRoute == Routes.EXPORT) {
Get.back();
} else {
Get.toNamed(Routes.EXPORT);
}
},
),
ListTile(
leading: Icon(Icons.recent_actors_rounded),
title: Text('Acerca de'),
onTap: () {
if (Get.currentRoute == Routes.ACERCA) {
Get.back();
} else {
Get.toNamed(Routes.ACERCA);
}
},
),
],
),
);
}
}
And the home part is:
import 'package:vakuprfid/app/modules/widgets/side_bar.dart';//import widget
class HomeView extends GetView<HomeController> {
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: SideBar(),
body: ...
);
}
}
This is the result:
For the main content put all the different view into a list and put it into PageView. And create a custom navigator and put these two widget into a Row:
Controller:
class SettingsController extends GetxController {
final PageController pageController =
PageController(initialPage: 1, keepPage: true);
}
Sidebar:
class MySideNavigation extends StatefulWidget {
MySideNavigation({Key? key}) : super(key: key);
#override
State<MySideNavigation> createState() => _MySideNavigationState();
}
class _MySideNavigationState extends State<MySideNavigation> {
#override
Widget build(BuildContext context) {
final SettingsController c = Get.find();
return NavigationRail(
selectedIndex: c.selectedViewIndex.value,
onDestinationSelected: (value) async {
setState(() {
c.selectedViewIndex(value);
c.pageController.jumpToPage(
value,
// duration: Duration(milliseconds: 500), curve: Curves.decelerate
);
});
},
labelType: NavigationRailLabelType.selected,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.map_outlined),
selectedIcon: Icon(Icons.map_rounded),
label: Text(
'نقشه ها',
style: TextStyle(fontSize: 14, fontFamily: 'Vazir'),
),
),
NavigationRailDestination(
icon: Icon(Icons.map_outlined),
selectedIcon: Icon(Icons.map_rounded),
label: Text(
'نقشه ها',
style: TextStyle(fontSize: 14, fontFamily: 'Vazir'),
),
),
NavigationRailDestination(
icon: Icon(Icons.person_outline),
selectedIcon: Icon(Icons.person),
label: Text(
'پروفایل',
style: TextStyle(fontSize: 14, fontFamily: 'Vazir'),
),
),
],
);
}
}
GotFatherView:
class GodFatherView extends StatelessWidget {
GodFatherView({Key? key}) : super(key: key);
final PageStorageBucket bucket = PageStorageBucket();
final SettingsController c = Get.find();
List<Widget> pages = [
const KeepAlivePage(Page1()),
KeepAlivePage(Page2()),
const KeepAlivePage(Page3()),
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: [
MySideNavigation(),
Expanded(
child: PageView(
controller: c.pageController,
children: pages,
),
)
],
));
}
}
tap on below link to open screenshot: I don't have enough reputation to post image :))))))
Screeshot
Give a special attention to the sidebar navigator in MySideNavigation class:
NavigationRail(
selectedIndex: c.selectedViewIndex.value,
onDestinationSelected: (value) async {
setState(() {
c.pageController.jumpToPage(value);
});
},
When user tap on each NavigationRailDestination ,onDestinationSelected function will be called with an index. The index are representing the index of the destination view. Example: When user on [Page1() -> index:0] tab on the second NavigationRailDestination the index inside of function is 1, so you can use the PageController to navigate into [Page2() -> index:1].
Attention, Attention, More Attention:
If you don't like to lose the state(I mean when u navigate to another view and back to previous view don't rebuild it again). Sometimes we need to keep the state of widget, we change something, write something into a text field and etc. If you don't wrap it with this widget all the data will be loosed(or you can save it through another way).
Wrap your widget with this Widget see the GodFather View I wrap all pages with KeepAlivePage, In this widget I extend State of the widget with 'AutomaticKeepAliveClientMixin' and override its value bool get wantKeepAlive => true; .
import 'package:flutter/material.dart';
class KeepAlivePage extends StatefulWidget {
const KeepAlivePage(this.child, {Key? key}) : super(key: key);
final child;
#override
State<KeepAlivePage> createState() => _KeepAlivePageState();
}
class _KeepAlivePageState extends State<KeepAlivePage>
with AutomaticKeepAliveClientMixin {
#override
Widget build(BuildContext context) {
super.build(context);
return widget.child;
}
#override
// TODO: implement wantKeepAlive
bool get wantKeepAlive => true;
}
it's easy,just let your right conent use GetMaterialApp and the route change is render right concent, then left sidler is a component warp your menuslider,
last control you left slider menuchange index.
show my code
Widget build(BuildContext context) {
return ScreenUtilInit(
designSize: const Size(dessignWidth, dessignHeight),
builder: () => BarcodeKeyboardListener(
onBarcodeScanned: (String codeValue) {},
child: Material(
child: MaterialApp(
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: const [
Locale('zh', 'CH'),
Locale('en', 'US'),
],
home: Row(
children: [
Material(
child: SliderMenu(),
),
Expanded(
child: GetMaterialApp(
debugShowCheckedModeBanner: false,
enableLog: true,
navigatorKey: Get.key,
routingCallback: RouteChangeMiddleWare.observer,
logWriterCallback: Logger.write,
initialRoute: AppPages.INITIAL,
getPages: AppPages.routes,
unknownRoute: AppPages.unknownRoute,
builder: EasyLoading.init(),
onInit: () =>
{logger.v('Global.CONFIG', AppConfig)}))
],
)),
)));
}```
hope to help you;

Can someone check my Dart code and tell me where I'm making mistake in returning data from my screen as a ListView

I am stuck here for the past 20 days in returning data in my app from the other screen. I'm new to programming and need help. I've been searching through all the internet to find an answer related to my query but nothing is helping though. I ask my fellow SO guys to please help.
You can look at the entire code which I've made open here.
My code:
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(30),
child: Stack(
alignment: Alignment.bottomRight,
children: <Widget>[
FloatingActionButton(
child: Icon(
Icons.add,
color: Colors.blue,
),
onPressed: () async {
final newList = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavoriteList(),
),
);
setState(() {
return ListView.builder(
itemCount: newList.length,
itemBuilder: (context, index){
return Container(
child: Text('item: $newList'),
);
},
);
});
},
)
],
),
);
}
}
The screen where Navigator.pop() is used:
final Set saved = Set();
class FavoriteList extends StatefulWidget {
#override
_FavoriteListState createState() => _FavoriteListState();
}
class _FavoriteListState extends State<FavoriteList> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add to Favorites!'),
centerTitle: true,
backgroundColor: Colors.red),
body: SafeArea(
child: ListView.builder(
itemCount: 53,
itemBuilder: (context, index) {
return CheckboxListTile(
activeColor: Colors.red,
checkColor: Colors.white,
value: saved.contains(index),
onChanged: (val) {
setState(() {
// isChecked = val; // changed
// if(val == true){ // changed
// __saved.add(context); // changed
// } else{ // changed
// __saved.remove(context); // changed
// } // changed
if (val == true) {
saved.add(index);
} else {
saved.remove(index);
}
});
},
title: Row(
children: <Widget>[
Image.asset('lib/images/${images[index]}'),
SizedBox(
width: 10,
),
Text(nameOfSite[index]),
],
),
);
},
),
),
floatingActionButton: FloatingActionButton(
foregroundColor: Colors.red,
child: Icon(Icons.check),
onPressed: () {
Navigator.pop<Set>(context, saved);
},
),
);
}
}
Here is the SecondPage and FavoriteList that I made
import 'package:flutter/material.dart';
import 'package:aioapp2/lists.dart';
Set<int> favorites = {};
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.expand,
children: <Widget>[
_getFavoriteList(),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: FloatingActionButton(
child: Icon(
Icons.edit,
color: Colors.blue,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditFavorites(),
),
).then((updatedFavorites) {
if (updatedFavorites != null)
setState(() {
favorites = updatedFavorites;
});
});
},
),
),
)
],
);
}
Widget _getFavoriteList() {
if (favorites?.isNotEmpty == true)
return _FavoriteList();
else
return _EmptyFavoriteList();
}
}
class _EmptyFavoriteList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Flexible(
child: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Add Your Favorite Sites Here!❤',
style: TextStyle(color: Colors.white),
),
Icon(
Icons.favorite,
size: 150,
color: Colors.blue[100],
),
],
),
),
),
),
],
);
}
}
class _FavoriteList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: favorites.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage('lib/images/${images[index]}'),
),
title: Text(nameOfSite[favorites.elementAt(index)]),
);
},
);
}
}
//Its FavoriteList Page. I changed the name
class EditFavorites extends StatefulWidget {
#override
_EditFavoritesState createState() => _EditFavoritesState();
}
class _EditFavoritesState extends State<EditFavorites> {
final _editableFavorites = <int>{};
#override
void initState() {
_editableFavorites.addAll(favorites);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add to Favorites!'),
centerTitle: true,
backgroundColor: Colors.red,
actions: <Widget>[
IconButton(
icon: Icon(Icons.done),
onPressed: () {
Navigator.pop<Set>(context, _editableFavorites);
},
)
],
),
//backgroundColor: Colors.indigo,
body: SafeArea(
child: ListView.builder(
itemCount: nameOfSite.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage('lib/images/${images[index]}'),
),
title: Text(nameOfSite[index]),
trailing: IconButton(
icon: _editableFavorites.contains(index)
? Icon(
Icons.favorite,
color: Colors.red,
)
: Icon(
Icons.favorite_border,
color: Colors.grey,
),
onPressed: () {
setState(() {
if (_editableFavorites.contains(index))
_editableFavorites.remove(index);
else
_editableFavorites.add(index);
});
},
),
);
},
),
),
);
}
}
Just replace secondtab.dart with this code.
You can copy paste run full code below
You have to move out return ListView to the same layer with FloatingActionButton
working demo
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SecondPage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
Set newList = {};
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(30),
child: Stack(
alignment: Alignment.bottomRight,
children: <Widget>[
ListView.builder(
itemCount: newList.length,
itemBuilder: (context, index) {
return Container(
child: Text('item: ${newList.elementAt(index)}'),
);
},
),
FloatingActionButton(
child: Icon(
Icons.add,
color: Colors.blue,
),
onPressed: () async {
newList = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavoriteList(),
),
);
setState(() {});
},
)
],
),
);
}
}
final Set saved = Set();
class FavoriteList extends StatefulWidget {
#override
_FavoriteListState createState() => _FavoriteListState();
}
class _FavoriteListState extends State<FavoriteList> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add to Favorites!'),
centerTitle: true,
backgroundColor: Colors.red),
body: SafeArea(
child: ListView.builder(
itemCount: 53,
itemBuilder: (context, index) {
return CheckboxListTile(
activeColor: Colors.red,
checkColor: Colors.white,
value: saved.contains(index),
onChanged: (val) {
setState(() {
// isChecked = val; // changed
// if(val == true){ // changed
// __saved.add(context); // changed
// } else{ // changed
// __saved.remove(context); // changed
// } // changed
if (val == true) {
saved.add(index);
} else {
saved.remove(index);
}
});
},
title: Row(
children: <Widget>[
//Image.asset('lib/images/${images[index]}'),
SizedBox(
width: 10,
),
Text('nameOfSite[index]'),
],
),
);
},
),
),
floatingActionButton: FloatingActionButton(
foregroundColor: Colors.red,
child: Icon(Icons.check),
onPressed: () {
Navigator.pop<Set>(context, saved);
},
),
);
}
}

Change color of Theme

I wanted to change the color of the counter in my app. I want to do that: change the color of the counter to blue when counter bigger than 0. if counter smaller than 0 change the color of the counter to red.if counter equal to 0 change the color of the counter to green. is it possible? I did just for 2 colors.
it is my codes :
import 'package:flutter/material.dart';
void main() {
runApp(Myapp());
}
class Myapp extends StatefulWidget {
#override
_MyappState createState() => _MyappState();
}
class _MyappState extends State<Myapp> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Myhomepage(
title: "My Home Page",
),
);
}
}
class Myhomepage extends StatefulWidget {
final String title;
Myhomepage({this.title});
#override
_MyhomepageState createState() => _MyhomepageState();
}
class _MyhomepageState extends State<Myhomepage> {
int counter = 0;
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
backgroundColor: Colors.grey[850],
onPressed: () {
setState(() {
counter++;
});
}),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text(
"Increase",
),
color: Colors.green,
onPressed: () {
setState(() {
counter++;
});
},
),
Text("The count of press button:"),
Text(
"$counter",
style: Theme.of(context).textTheme.display2.copyWith(color: counter<=0 ? Colors.red : Colors.blue)
),
RaisedButton(
child: Text(
"Decrease",
),
color: Colors.red,
onPressed: () {
setState(() {
counter--;
});
},
),
],
),
),
);
}
}
it is my results :
Here's one way you can implement the system you want. I just made a function that returns the desired color.
class _MyhomepageState extends State<Myhomepage> {
int counter = 0;
Color _getCounterColor() {
if (counter > 0) return Colors.blue;
else if (counter < 0) return Colors.red;
else return Colors.green;
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
backgroundColor: Colors.grey[850],
onPressed: () {
setState(() {
counter++;
});
}),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text(
"Increase",
),
color: Colors.green,
onPressed: () {
setState(() {
counter++;
});
},
),
Text("The count of press button:"),
Text(
"$counter",
style: Theme.of(context).textTheme.display2.copyWith(color: _getCounterColor()),
),
RaisedButton(
child: Text(
"Decrease",
),
color: Colors.red,
onPressed: () {
setState(() {
counter--;
});
},
),
],
),
),
);
}
}

Alert box with multi select chip in flutter

I have a multiselect chip in my app , but when since the data in the AlertDialog depends dynamically, it will be 1 or 100, so I have added SingleChildScrollView over the alert Dialog to give scrolling if there are more entries , but when I added SingleChildScrollView my alert box goes to top of the screen like this, I want it to align in center,
If I removed the SingleChildScrollView then It will come like this which I wanted. but If there are lot of entries I cant select because It cant cover the entire data?
Is there any way where I can align it to center of screen with scroll enabled?
Thanks
showDialog(
context: context,
builder: (BuildContext context) {
return SingleChildScrollView(
child: AlertDialog(
title: Text("choose items"),
content: MultiSelectChip(
reportList,
onSelectionChanged: (selectedList) {
setState(() {
listSelectedItem = selectedList;
});
},
),
actions: <Widget>[
FlatButton(
child: Text("CANCEL"),
onPressed: () {
setState(() {
dropdownSelected = null;
listSelectedItem.clear();
});
Navigator.of(context).pop();
}),
In AlertDialog's content use Container and constraints, and in Container's child wrap SingleChildScrollView then wrap MultiSelectChip
code snippet
return AlertDialog(
title: Text("Report Video"),
content: Container(
constraints: BoxConstraints(
maxHeight: 100.0,
),
child: SingleChildScrollView(
child: MultiSelectChip(
reportList,
onSelectionChanged: (selectedList) {
setState(() {
selectedReportList = selectedList;
});
},
),
),
),
actions: <Widget>[
FlatButton(
child: Text("Report"),
onPressed: () => Navigator.of(context).pop(),
)
],
);
})
full code
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: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> reportList = [
"Not relevant",
"Illegal",
"Spam",
"Offensive",
"Uncivil",
"a123",
"b234",
"c2314",
"aaaa",
"a",
"1Not relevant",
"2Illegal",
"3Spam",
"4Offensive",
"5Uncivil",
"6a123",
"7b234",
"8c2314",
"9aaaa",
"0a",
"Not relevant",
"Illegal",
"Spam",
"Offensive",
"Uncivil",
"a123",
"b234",
"c2314",
"aaaa",
"a",
"1Not relevant",
"2Illegal",
"3Spam",
"4Offensive",
"5Uncivil",
"6a123",
"7b234",
"8c2314",
"9aaaa",
"0a",
];
List<String> selectedReportList = List();
_showReportDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
//Here we will build the content of the dialog
return AlertDialog(
title: Text("Report Video"),
content: Container(
constraints: BoxConstraints(
maxHeight: 100.0,
),
child: SingleChildScrollView(
child: MultiSelectChip(
reportList,
onSelectionChanged: (selectedList) {
setState(() {
selectedReportList = selectedList;
});
},
),
),
),
actions: <Widget>[
FlatButton(
child: Text("Report"),
onPressed: () => Navigator.of(context).pop(),
)
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text("Report"),
onPressed: () => _showReportDialog(),
),
Text(selectedReportList.join(" , ")),
],
),
),
);
}
}
class MultiSelectChip extends StatefulWidget {
final List<String> reportList;
final Function(List<String>) onSelectionChanged;
MultiSelectChip(this.reportList, {this.onSelectionChanged});
#override
_MultiSelectChipState createState() => _MultiSelectChipState();
}
class _MultiSelectChipState extends State<MultiSelectChip> {
// String selectedChoice = "";
List<String> selectedChoices = List();
_buildChoiceList() {
List<Widget> choices = List();
widget.reportList.forEach((item) {
choices.add(Container(
padding: const EdgeInsets.all(2.0),
child: ChoiceChip(
label: Text(item),
selected: selectedChoices.contains(item),
onSelected: (selected) {
setState(() {
selectedChoices.contains(item)
? selectedChoices.remove(item)
: selectedChoices.add(item);
widget.onSelectionChanged(selectedChoices);
});
},
),
));
});
return choices;
}
#override
Widget build(BuildContext context) {
return Wrap(
children: _buildChoiceList(),
);
}
}