FLUTTER UI Selection box (with Container and SetState) selected but nothing happen - flutter

Halo,
I have problem with my Selected Container,
it changed on main page when selected, but didn't change when selected in bottomsheet.
here's the video link :
https://youtube.com/shorts/hzPNNQB6Gws?feature=share
here is the screenshoot :
This is how I call in bottomsheet :
bottomsheet: Container(
~~
~~
child: OutlinedButton(
child: Text("Buy Now"),
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return bottomContainer(context);
});
},
),
)
here's the bottomContainer widget code :
Widget bottomContainer(BuildContext context) {
~~
~~
return Wrap(
spacing: 8.0,
runSpacing: 4.0,
children: <Widget> [
...List.generate(
listVariant.length,
(index) => selectedButton(
index: index,
text: listVariant[index],
),
),
],
),
~~
~~
}
and here's selectedButton widget full code :
Widget selectedButton({required String text, required int index}) {
return InkWell(
splashColor: Colors.cyanAccent,
onTap: () {
setState(() {
_selectedVariant = index;
print('$index, $text');
});
},
child: Container(
height: 36,
width: text.length.toDouble() *9,
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(10)),
border: Border.all(
width: 1.5,
color: const Color.fromRGBO(78, 125, 150, 1),
),
color: index == _selectedVariant
? const Color.fromRGBO(78, 125, 150, 0.5)
: Colors.white,
),
child: Center(
child: Text(text,
textAlign: TextAlign.center,
style: const TextStyle(
color: Color.fromRGBO(78, 125, 150, 1),
fontSize: 13,
fontWeight: FontWeight.w700
),
),
)
),
);
}
IDK where's the problem because you can see in video that it was working on body, but didn't work in bottomsheet widget.
*All of this code was in one class state

The reason this is happening is that you try to update your main page not your showModalBottomSheet, first change your selectedButton to this:
Widget selectedButton({required String text, required int index, required Function() onTap}) {
return InkWell(
splashColor: Colors.cyanAccent,
onTap: onTap,
child: ...
);
}
then change your bottomContainer to this:
Widget bottomContainer(BuildContext context, void Function(void Function()) innerSetState) {
~~
~~
return Wrap(
spacing: 8.0,
runSpacing: 4.0,
children: <Widget> [
...List.generate(
listVariant.length,
(index) => selectedButton(
onTap:(){
innerSetState(() {
_selectedVariant = index;
});
},
index: index,
text: listVariant[index],
),
),
],
),
~~
~~
}
then change your showModalBottomSheet to this:
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, innerSetState) {
return bottomContainer(context, innerSetState);
},
),
});
},
Note: when you try to call selectedButton from your main page remember to pass these function to it:
selectedButton(
onTap:(){
setState(() {
_selectedVariant = index;
});
},
...
)

Related

Flutter > Unselect a RadioButton in a View.builder

I am not finding any answer for my question so I am hoping to find someone who can help.
I have a GridView with text buttons.
I can select the buttons, however I can't unselect any of them.
this is my code
#override
Widget build(BuildContext context) {
return TextButton(
onLongPress: () => showDialog<String>(
),
style: ButtonStyle(
side: MaterialStateProperty.all(BorderSide(
width: 5,
color: widget.isSelected ? Colors.black : Colors.white)),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))),
backgroundColor: MaterialStateProperty.all(widget.pickerColor),
elevation: MaterialStateProperty.all(10)),
onPressed: () {
widget.selectedCard(widget.index); //This selects the cards, how to unselect (if Statements?)
},
child: FittedBox(
fit: BoxFit.fitHeight,
child: Text(
widget.cardTitle,
style: TextStyle(
fontSize: 17,
color: useWhiteForeground(widget.pickerColor)
? const Color(0xffffffff)
: const Color(0xff000000),
),
),
),
);
}
}
This is the Grid
#override
Widget build(BuildContext context) {
return Consumer<MyCardData>(
builder: (context, cardData, child) {
return Padding(
padding: const EdgeInsets.all(10),
child: GridView.builder(
clipBehavior: Clip.none,
itemBuilder: (context, index) {
final card = cardData.cards[index];
return MyCard(
selectedCard,
index: index,
isSelected: _selectedCard == index,
cardTitle: card.name,
pickerColor: card.cardColor,
deleteCallback: () {
cardData.deleteCallback(card);
},
);
},
itemCount: cardData.cardCount,
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 150,
childAspectRatio: 2.5 / 1,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
),
);
},
);
}
}
feel free to use my git to see the full code
get from version control
since you want to make a single selection, it will need a simple workaround.
int _selectedCard = -1;
selectedCard(index) {
// this condition is when user press the same button
// set the _selectedCard back into -1
if (_selectedCard == index) {
setState(() {
_selectedCard = -1;
});
} else{
setState(() {
_selectedCard = index;
});
}
}

Update item widget from local database list

I'm using a ready-made local database in my application and the problem is that I can't update one item from the list. If I add a chapter to favorites, then the button's state is updated only after the page is reopened. Likewise, the favorites list is updated only when the page is reopened. Right now when I add/remove favorites, I dynamically load the entire list so that it updates the values, but I only need to update one item, how can I do this using a provider? I didn’t give code examples, because I want to understand exactly the logic of actions
UPD:
My code:
#override
Widget build(BuildContext context) {
return FutureBuilder<List>(
future: _databaseQuery.getAllChapters(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return snapshot.connectionState == ConnectionState.done &&
snapshot.hasData
? CupertinoScrollbar(
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, int index) {
return MainChapterItem(
item: snapshot.data![index],
);
},
),
)
: const Center(
child: CircularProgressIndicator.adaptive(),
);
},
);
}
Item:
final MainChapterItemModel item;
#override
Widget build(BuildContext context) {
return Material(
child: InkWell(
child: Container(
padding: const EdgeInsets.all(8),
child: Row(
children: [
IconButton(
icon: item.favoriteState == 0
? const Icon(CupertinoIcons.bookmark)
: const Icon(CupertinoIcons.bookmark_fill),
splashRadius: 22,
splashColor: const Color(0xff81b9b0),
onPressed: () {
context.read<BookmarkButtonState>().addRemoveChapterBookmark(
item.favoriteState == 0 ? 1 : 0, item.id);
},
),
const SizedBox(
width: 8,
),
Flexible(
child: ListTile(
contentPadding: EdgeInsets.zero,
title: Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
item.chapterNumber,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
subtitle: Html(
data: item.chapterTitle,
style: {
'#': Style(
fontSize: const FontSize(17),
padding: EdgeInsets.zero,
margin: EdgeInsets.zero,
),
'small': Style(
fontSize: const FontSize(8),
),
'a': Style(
fontSize: const FontSize(14),
color: Colors.blue,
),
},
),
),
),
],
),
),
onTap: () {},
),
);
}
The problem is that when I add to favorites or delete, the button state is not updated. And in the favorites list, the item is not deleted on click, but it disappears after the page is reopened:
IconButton(
icon: item.favoriteState == 0
? const Icon(CupertinoIcons.bookmark)
: const Icon(CupertinoIcons.bookmark_fill),
splashRadius: 22,
splashColor: const Color(0xff81b9b0),
onPressed: () {
context.read<BookmarkButtonState>().addRemoveChapterBookmark(
item.favoriteState == 0 ? 1 : 0, item.id);
},
),
Provider code:
final DatabaseQuery _databaseQuery = DatabaseQuery();
DatabaseQuery get getDatabaseQuery => _databaseQuery;
addRemoveChapterBookmark(int state, int chapterId) {
_databaseQuery.addRemoveFavoriteChapter(state, chapterId);
notifyListeners();
I solved the problem by signing all lists to listen to databaseQuery in the provider:
future: context.watch<BookmarkButtonState>().getDatabaseQuery.getAllChapters(),

gestureEvent or PointerEvent on longPressed DialogBox

How to add tap or longpress (any gestureDector event) on longpressed DialogBox
clicking on icons on popop after showing that, can we swipe on icons and getting action like with click?
hear i'am, using "OverlyEntery" to show dialog, iam using overlyEntry because it will keep the gesture longpress event, it's work fine when longpress show the Dialog and disappear when longpressEnd event occurred, but the problem is after open a dialog Box,
in Dialog box i was not able to add any event, hear i want like instagram image preview.
Thank you.
import 'package:flutter/material.dart';
class Explore extends StatelessWidget {
Explore({Key? key}) : super(key: key);
OverlayEntry _popUp({required String url}) {
return OverlayEntry(
builder: (context) => Dialog(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: double.infinity,
padding: EdgeInsets.all(10.0),
color: Colors.black,
child: Center(
child: Text(
"Trip Body name",
style: TextStyle(color: Colors.white),
)),
),
Image.asset(url),
Container(
color: Colors.black,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
GestureDetector(
onLongPress: () {
print("press1");
},
onLongPressCancel: () {
print("press2");
},
onLongPressDown: (e) {
print("press3");
},
onLongPressMoveUpdate: (d) {
print("press4");
},
child: Container(
child: const Icon(
Icons.favorite,
color: Colors.white,
)),
),
Icon(Icons.save)
],
),
)
],
)));
}
OverlayEntry? _popUpDialog;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: StaggeredGridView.countBuilder(
// controller: _scrollController,
crossAxisCount: 2,
itemCount: 50,
itemBuilder: (BuildContext context, int index) => InkWell(
onTap: () {
},
child: GestureDetector(
// behavior: HitTestBehavior.deferToChild,
onLongPress: () {
_popUpDialog = _popUp(
url: 'assets/images/a' +
((index < 15)
? index.toString()
: index > 20
? '3'
: (index - 10).toString()) +
'.jpeg');
Overlay.of(context)!.insert(_popUpDialog!);
},
onLongPressEnd: (d) {
_popUpDialog!.remove();
},
child: Image.asset((
'assets/images/a' +
((index < 15)
? index.toString()
: index > 20
? '3'
: (index - 10).toString()) +
'.jpeg'
)),
),
staggeredTileBuilder: (int index) => StaggeredTile.count(
1, isForReel(index: index) ? 1.5 : 1), // 2,11,23,30,44
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
),
),
)
]
)
);
}
}
Try to add Gesture Detecter on body of DialogBox rather than SubViews.

How to make just one ExpansionPanel, in an ExpansionPanelList different to the others? flutter

As the question suggests I have an ExpansionPanelList, one ExpansionPanel (the last one or the 7th one) should have 2 additional buttons, but how can I add them just in this one last panel & not in all the others as well?
This is the code of my whole Expansion panel, as Im not sure where you have to add the behaviour, but guessing in the body of the ExpansionPanel (close to line 40):
class ExpansionList extends StatefulWidget {
final Info info;
const ExpansionList({
Key key,
this.info,
}) : super(key: key);
#override
_ExpansionListState createState() => _ExpansionListState();
}
class _ExpansionListState extends State<ExpansionList> {
Widget _buildListPanel() {
return Container(
child: Theme(
data: Theme.of(context).copyWith(
cardColor: Color(0xffDDBEA9),
),
child: ExpansionPanelList(
dividerColor: Colors.transparent,
elevation: 0,
expansionCallback: (int index, bool isExpanded) {
setState(() {
infos[index].isExpanded = !isExpanded;
});
},
children: infos.map<ExpansionPanel>((Info info) {
return ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return ListTile(
title: !isExpanded
? Text(
info.headerValue,
) //code if above statement is true
: Text(
info.headerValue,
textScaleFactor: 1.3,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
);
},
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
color: Color(0xffFFE8D6),
borderRadius: BorderRadius.circular(25)),
child: Column(
children: [
ListView.separated(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
padding: EdgeInsets.only(left: 40.0,),
itemCount: info.expandedValueData.length,
itemBuilder: (context, index) {
return CheckboxListTile(
title: Text(info.expandedValueData[index].title,
style: TextStyle(
decoration: info.expandedValueData[index]
.completed
? TextDecoration.lineThrough
: null)),
value: info.expandedValueData[index].completed,
onChanged: (value) {
setState(() {
// Here you toggle the checked item state
infos.firstWhere(
(currentInfo) => info == currentInfo)
..expandedValueData[index].completed =
value;
});
});
},
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 20,
);
},
),
Row(children: [
SizedBox(
width: MediaQuery.of(context).size.width * 0.16),
Text("Abschnitt bis zum Neustart löschen"),
SizedBox(
width: MediaQuery.of(context).size.width * 0.11),
IconButton(
icon: Icon(Icons.delete),
onPressed: () {
setState(() {
infos.removeWhere(
(currentInfo) => info == currentInfo);
});
},
)
]),
],
),
),
),
isExpanded: info.isExpanded);
}).toList(),
),
),
);
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
child: _buildListPanel(),
),
);
}
}
Thanks for suggestions!
Hi Just add a field (if you already do not have one) in the info object that will allow you to change the widget that is inflated based on that field.
For example
...
children: infos.map<ExpansionPanel>((Info info) {
return ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return info.type == TYPE_A ? TypeAWidgetHeader(info) : TypeBWidgetHeader(info);
body: info.type == TYPE_A ? TypeAWidgetBody(info) : TypeBWidgetBody(info);
...

Return variable from current screen to previous screen

So I am implementing a 'settings' view in my Flutter app. The idea is all settings will appear in a ListView, and when the user will click on a ListTile, a showModalBottomSheet will pop where the user will be able to manipulate the setting. The only problem I am having is I am unable to migrate the showModalBottomSheet to a separate class as I cannot make the new function (outside the class) return the manipulated setting variable. This has lead to a messy code, all in a single class.
class Page extends StatefulWidget {
Page({Key key}) : super(key: key);
#override
_Page createState() => _Page();
}
class _Page extends State<Page> {
var value;
#override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
ListTile(
title: Text("Age"),
trailing: Text(value),
onTap: () {
setState(() {
value = _valueSelector(); // This doesn't work, but to give an idea what I want
});
},
),
],
);
}
}
int _valueSelector(context) { // Doesn't return
var age = 0;
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Wrap(
children: [
Column(
children: <Widget>[
Slider(
value: age.toDouble(),
min: 0,
max: 18,
divisions: 18,
onChanged: (value) {
setState(() {
age = value.toInt();
});
},
),
],
),
],
);
});
},
).whenComplete(() {
return age; // Not sure if return is supposed to be here
});
}
How can I implement showModalBottomSheet in a separate class and just make it return the variable representing the setting chosen by the user?
You can try the below code,
First, create a class custom_bottom_sheet.dart and add the below code. You can use it everywhere in the project. And also use this library modal_bottom_sheet: ^0.2.0+1 to get the showMaterialModalBottomSheet.
customBottomSheet(BuildContext context, {#required Widget widget}) async {
return await showMaterialModalBottomSheet(
context: context,
backgroundColor: AppColors.transparent_100,
barrierColor: AppColors.black_75,
isDismissible: false,
enableDrag: true,
builder: (_, ScrollController scrollController) {
return widget;
},
);
}
Sample example code:
Create another class called bottom_sheet_example.dart and add the below code.
class BottomSheetExample {
static Future getSheet(BuildContext _context,
{ValueChanged<bool> onChanged}) async {
await customBottomSheet(
_context,
widget: SafeArea(
child: Container(
padding: EdgeInsets.only(left: 40.0, right: 40.0),
height: 170.0,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(27.0),
topRight: Radius.circular(27.0))),
child: Container(
padding: EdgeInsets.only(top: 32),
child: Column(
children: [
Text("Were you at Queen Victoria Building?"),
SizedBox(height: 48),
Row(
children: [
Expanded(
child: RaisedButton(
child: Text("No"),
onPressed: () {
Navigator.of(_context).pop();
onChanged(false);
},
),
),
SizedBox(width: 18),
Expanded(
child: RaisedButton(
child: Text("Yes"),
onPressed: () {
Navigator.of(_context).pop();
onChanged(true);
},
),
),
],
),
SizedBox(height: 24),
],
),
),
)),
);
}
}
Button click to show the bottom sheet
#override
Widget build(BuildContext context) {
return Scaffold(
body: yourBodyWidget(),
bottomNavigationBar: Container(
height: 40,
width: double.infinity,
child: FlatButton(
onPressed: () {
/// call BottomSheetExample class
BottomSheetExample.getSheet(
context,
onChanged: (bool result) async {
///
/// add your code
},
);
},
child: Text("show bottom sheet")),
),
);
}
In onChanged callback you can return your value(obj/String/num/bool/list).
Thank you!