Flutter - How to select an item (tag) automatically in the UI - List<dynamic> - flutter

I am trying to preselect a particular tag shown on the right of the image.
However, I am unable to figure out where to set it. The tags are coming from an API (Postgres backend).
Once it is built to a list of overlay as shown on the right again in the screenshot. I just wanted it to preselect, "Morning", "Evening" or "Daytime" based on the time of the day.
To start off with, I am not able to preselect anything in "selectedTags". This can only be done manually by the user when clicked on a tag.
The method is shared below.
showTagPicker(context, allTags) async {
await showModalBottomSheet(
isDismissible: false,
enableDrag: false,
backgroundColor: Colors.transparent,
isScrollControlled: true,
context: context,
builder: (builder) => Center(
child: Container(
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
color: Colors.white,
),
margin: EdgeInsets.all(16),
padding: EdgeInsets.all(24),
child: ListView(
shrinkWrap: true,
children: <Widget>[
Text(
"Please pick your tags",
style: TextStyle(fontSize: 16),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: TagPicker(
height: MediaQuery.of(context).size.height * .6,
tags: allTags,
onTagSelected: (_selectedTags) {
selectedTags = _selectedTags;
print("----->");
print(selectedTags);
print("<-----");
},
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
RaisedButton(
color: PRIMARY,
textColor: WHITE,
onPressed: () {
Navigator.of(context).pop();
navigateToAnalysis(context);
},
child: Text("Save"),
),
],
)
],
),
),
),
);
}
I tried, adding "print" to debug and see what and where things are being set but I did not get any further, I have also shown the debug screen if it helps.
Any direction here to preselect one/many tags would be helpful.
Please let me know if I must provide additional details to solve this.
Also, I know there are several things in the code which might be wrong, it is inherited code and I am struggling a bit.
Edit: Including TagPicker. It is not a public library but our widget.
class TagPicker extends StatefulWidget {
const TagPicker(
{Key key, this.height, this.tags, this.onTagSelected, this.selectedTags})
: super(key: key);
#override
TagPickerState createState() => TagPickerState();
final double height;
final List tags;
final List selectedTags;
final Function onTagSelected;
}
class TagPickerState extends State<TagPicker> {
List selectedTags = [];
#override
void initState() {
super.initState();
if (widget.selectedTags != null) {
setState(() {
selectedTags = widget.selectedTags;
});
}
}
#override
Widget build(BuildContext context) {
return widget.tags != null
? Container(
constraints: widget.height != null
? BoxConstraints(maxHeight: widget.height, minHeight: 60)
: BoxConstraints(),
child: SingleChildScrollView(
child: Wrap(
spacing: 0.0,
children: List.generate(
widget.tags.length,
(index) {
return Padding(
padding: const EdgeInsets.only(right: 4.0),
child: ChoiceChip(
selectedColor: PRIMARY,
labelStyle: TextStyle(
fontSize: 12,
color: selectedTags.contains(widget.tags[index])
? WHITE
: Colors.black),
label: Text(widget.tags[index]['tag_name']),
selected: selectedTags.contains(widget.tags[index]),
onSelected: (selected) {
setState(() {
selectedTags.contains(widget.tags[index])
? selectedTags.remove(widget.tags[index])
: selectedTags.add(widget.tags[index]);
widget.onTagSelected(selectedTags);
});
},
),
);
},
),
),
),
)
: Container();
}
}

Pass selectedTags as an argument to TagPicker and modify TagPicker to render an initial set of selected tags. As before onTagSelected callback will provide an updated set.

Related

Flutter responsive Row or Row alternative suggestions

I'm pretty new to Flutter, and I wanted to create a folder effect with tabs for my portfolio website where you click on the tabs to change what displayed in the center of the folder. Right now the buttons are dynamically generated as children of a row widget. The problem is that at smaller screen widths the text is either too small or gets cut off altogether. I even tried to figure out how to do a sort of multi-line row but gave up.
What I would ideally like is that the buttons wrap such that any buttons that would make the parent too long are placed on a separate row. However, I'm open to any solution that allows all the tabs to fit on screen without the text in the buttons being super shrunk.
My current solutions as you can see is to just scale the text down at smaller screen widths so that its all at least visible. I'm guessing that I'm either going to have redesign the way I implement the effect, or there's some relatively simple solution that I'm not aware of. I also tried replacing the Row widget that wraps the FolderButtons to a Wrap with no other modifications and that just caused the text to disappear.
Note: The way its currently implemented assumes and depends upon the folder being a perfect square.
Below are Folder, FolderButton, and ScaleSize classes respectively:
class Folder extends StatefulWidget {
const Folder({super.key});
static Column? getStaticPages(String page, BuildContext context) {
Map<String, Column> pages = {
"Welcome": Column(
children: [
Text(
'Welcome',
style: TextStyle(color: Colors.deepPurpleAccent.shade100),
)
],
),
"Web Dev's Handbook": Column(
children: [
Text(
"Web Dev's Handbook",
style: TextStyle(color: Colors.deepPurpleAccent.shade100),
),
TextButton(
onPressed: () => {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Contents()))
},
child: const Text("Go"))
],
),
"Interactive Resume": Column(
children: [
Text(
'Interactive Resume',
style: TextStyle(color: Colors.deepPurpleAccent.shade100),
)
],
),
"Settings": Column(
children: [
Text(
'Settings',
style: TextStyle(color: Colors.deepPurpleAccent.shade100),
)
],
),
"Credits": Column(
children: [
Text(
'Credits',
style: TextStyle(color: Colors.deepPurpleAccent.shade100),
)
],
),
};
return pages[page];
}
static List<Map<String, dynamic>> staticTabs = [
{"title": "Welcome"},
{"title": "Web Dev's Handbook"},
{"title": "Interactive Resume"},
{"title": "Settings"},
{"title": "Credits"},
];
static List<FolderButton> generateTabs(int selectedTab, Function setTab) {
List<FolderButton> newTabs = [];
for (int x = 0; x < staticTabs.length; x++) {
bool selected;
if (selectedTab == x) {
selected = true;
} else {
selected = false;
}
newTabs.add(FolderButton(
title: staticTabs[x]["title"],
count: x,
selected: selected,
setTab: setTab));
}
return newTabs;
}
#override
State<Folder> createState() => _FolderState();
}
class _FolderState extends State<Folder> {
int _selectedTab = 0;
void _setTab(int count) {
setState(() {
_selectedTab = count;
});
}
#override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.only(left: 1, right: 1, top: 20),
child: SizedBox(
height: 750,
width: 750,
child: Column(
children: [
Flexible(
flex: 1,
child: Padding(
padding: const EdgeInsets.only(left: 7.0),
child: Row(
children: Folder.generateTabs(_selectedTab, _setTab),
),
),
),
Flexible(
flex: 15,
fit: FlexFit.tight,
child: Container(
decoration: BoxDecoration(
color: Colors.deepPurpleAccent,
borderRadius: BorderRadius.circular(5)),
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
width: 800,
decoration:
const BoxDecoration(color: Colors.deepPurple),
child: Folder.getStaticPages(
Folder.staticTabs[_selectedTab]["title"], context)),
),
),
),
],
),
),
),
);
}
}
class FolderButton extends StatefulWidget {
const FolderButton(
{super.key,
required this.title,
required this.count,
this.selected = false,
required this.setTab});
final String title;
final int count;
final bool selected;
final Function setTab;
static final theme = <String, dynamic>{
"button": <String, dynamic>{
"picked": <bool, ButtonStyle>{
true: TextButton.styleFrom(
backgroundColor: Colors.deepPurple,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(5), topRight: Radius.circular(5)),
side: BorderSide(
color: Colors.deepPurpleAccent,
strokeAlign: StrokeAlign.outside))),
false: TextButton.styleFrom(
backgroundColor: Colors.deepPurple,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(5), topRight: Radius.circular(5)),
side: BorderSide(
color: Colors.deepPurple, strokeAlign: StrokeAlign.outside)),
),
}
},
// TODO Make it so I don't need to do it like this
"padding": <bool, dynamic>{
true: const EdgeInsets.only(top: 3, left: 3, right: 3),
false: const EdgeInsets.only(top: 3, left: 3, right: 3)
}
};
static Color? getTabShading(selected) {
if (selected) {
return Colors.deepPurpleAccent;
}
return Colors.deepPurple;
}
static EdgeInsetsGeometry getTabPadding(selected) {
return theme["padding"][selected];
}
#override
State<FolderButton> createState() => _FolderButtonState();
}
class _FolderButtonState extends State<FolderButton> {
void changeSelected() {}
#override
Widget build(BuildContext context) {
return Flexible(
child: Container(
height: 100,
// Button Container
decoration: BoxDecoration(
// Container Decorations
color: FolderButton.getTabShading(widget.selected),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(5),
topRight: Radius.circular(5),
)),
// Button Padding
child: Padding(
padding: FolderButton.getTabPadding(widget.selected),
// Button
child: TextButton(
onPressed: () {
widget.setTab(widget.count);
},
// Style of button itself
style: FolderButton.theme["button"]?["picked"][widget.selected],
child: Text(
textAlign: TextAlign.center,
textScaleFactor: ScaleSize.textScaleFactor(context,
maxTextScaleFactor: 1.5),
// Text of the button
widget.title,
style: TextStyle(
color: Colors.deepPurpleAccent.shade100,
fontSize: 10,
height: 1))),
),
),
);
}
}
class ScaleSize {
static double textScaleFactor(BuildContext context,
{double maxTextScaleFactor = 2}) {
final width = MediaQuery.of(context).size.width;
double val = (width / 1400) * maxTextScaleFactor;
return max(1, min(val, maxTextScaleFactor));
}
}
Any general flutter tips, tricks, conventions, and/or all-around good ideas are appreciated.
Perhaps Wrap widget is what you need. It works just like a Row until you reach the limit of the horizontal size, and then places the next widget in a new "Row" below the previous.
Try using Expanded as a child for Row/Column or whatever you need there. I'm giving you a brief description from the flutter page. I think that for text that does not have a specific width it will be good.
https://api.flutter.dev/flutter/widgets/Expanded-class.html
The answer is simply to rebuild the component with Wrap as the parent to the Buttons as it wrap overflowing children below the rest. I will also be sure to maintain a bit more forethought in terms of responsive layout design while making use of the responsive framework package.

How to get data from firestore to List on flutter?

I wrote the code to get data from List to chips and when click chips the colour changed to blue. But I want to fetch data from firestore instead "words list".
Instead this words list ...
Database collection image
I want to display "WordName" field in the chips.
My code..
class uitry extends StatefulWidget {
const uitry({Key? key}) : super(key: key);
#override
State<uitry> createState() => _uitryState();
}
class _uitryState extends State<uitry> {
List<String> wordList = [
'Shopping',
'Brunch',
'Music',
'Road Trips',
'Tea',
'Trivia',
'Comedy',
'Clubbing',
'Drinking',
'Wine',
];
List<String> selectedWord = [];
List<String>? deSelectedWord = [];
#override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(Config.app_background4), fit: BoxFit.fill),
),
child: SafeArea(
child: Center(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 14, right: 0),
child: Column(
children: [
SizedBox(
width: width * 0.94,
height: height * 0.30,
child: Column(
children: <Widget>[
const SizedBox(height: 16),
Wrap(
children: wordList.map(
(word) {
bool isSelected = false;
if (selectedWord!.contains(word)) {
isSelected = true;
}
return GestureDetector(
onTap: () {
if (!selectedWord!.contains(word)) {
if (selectedWord!.length < 50) {
selectedWord!.add(word);
deSelectedWord!.removeWhere(
(element) => element == word);
setState(() {});
print(selectedWord);
}
} else {
selectedWord!.removeWhere(
(element) => element == word);
deSelectedWord!.add(word);
setState(() {
// selectedHobby.remove(hobby);
});
print(selectedWord);
print(deSelectedWord);
}
},
child: Container(
margin: const EdgeInsets.symmetric(
horizontal: 5, vertical: 4),
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 5, horizontal: 12),
decoration: BoxDecoration(
color: isSelected
? HexColor('#0000FF')
: HexColor('#D9D9D9'),
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: isSelected
? HexColor('#0000FF')
: HexColor('#D9D9D9'),
width: 2)),
child: Text(
word,
style: TextStyle(
color: isSelected
? Colors.black
: Colors.black,
fontSize: 14,
fontWeight: FontWeight.w600),
),
),
),
);
},
).toList(),
),
],
),
),
],
),
),
],
))),
),
);
}
}
How get that from firestore? I hope You can understand what I ask. Thank you!
I would do the following:
Initialize your list of words to an empty list
Use the initState method of the stateful widget to make a call to firestore to fetch all the documents that have the wordName property and get the word from the result and set it to a new list
Assign the new list to the wordList property and setState to re-render.
This would be it to get the words and set the chips with fetched words.
Keep in mind that since you are making an async call to firestore you should show some form of loading to tell the user you are fetching the data otherwise you would show and empty chip list until you fetch the data.

Saving state of a widget in Stepper flutter

I created a stepper (4 steps) with two buttons for next and previous. Each step has a form, and each form is in a widget in its own class.
The first problem is that every time I click the previous button, the data in the text fields disappear.
How can I preserve the state of each widget in each step?
The second problem, I want the last step to be a summary of what the user has entered in the previous steps. What is the best way to get the data from each step and display them in the last step?
I would really appreciate it if you could give me a solution. Thank you
I tried using AutomaticKeepAliveClientMixin but it didn't work .
import 'package:flutter/material.dart';
class CustomeStepper extends StatelessWidget {
final double width;
final List<IconData> icons;
final List<String> titles;
final int curStep;
final Color circleActiveColor;
final Color circleInactiveColor;
final Color iconActiveColor;
final Color iconInactiveColor;
final Color textActiveColor;
final Color textInactiveColor;
final double lineWidth = 4.0;
final List<Widget> content;
CustomeStepper(
{required this.icons,
required this.curStep,
required this.titles,
required this.width,
required this.circleActiveColor,
required this.circleInactiveColor,
required this.iconActiveColor,
required this.iconInactiveColor,
required this.textActiveColor,
required this.textInactiveColor,
required this.content})
: assert(curStep > 0 && curStep <= icons.length),
assert(width > 0);
#override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Container(
width: width,
padding: const EdgeInsets.only(
top: 32.0,
left: 24.0,
right: 24.0,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Row(
children: _iconViews(),
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: _titleViews(),
),
Expanded(
child: Container(
margin: const EdgeInsets.only(top: 16),
child: content[curStep - 1]),
)
],
)),
);
}
List<Widget> _iconViews() {
var list = <Widget>[];
icons.asMap().forEach((i, icon) {
var circleColor = (i == 0 || curStep >= i + 1)
? circleActiveColor
: circleInactiveColor;
var lineColor = (i == 0 || curStep >= i + 1)
? circleActiveColor
: circleInactiveColor;
var iconColor =
(i == 0 || curStep >= i + 1) ? iconActiveColor : iconInactiveColor;
list.add(
Container(
width: 50.0,
height: 50.0,
padding: const EdgeInsets.all(0),
child: Icon(
icon,
color: iconColor,
size: 25.0,
),
decoration: BoxDecoration(
color: circleColor,
borderRadius: const BorderRadius.all(
Radius.circular(25.0),
),
),
),
);
//line between icons
if (i != icons.length - 1) {
list.add(Expanded(
child: Container(
height: lineWidth,
color: lineColor,
)));
}
});
return list;
}
List<Widget> _titleViews() {
var list = <Widget>[];
titles.asMap().forEach((i, text) {
var _textColor =
(i == 0 || curStep > i + 1) ? textActiveColor : textInactiveColor;
list.add(
Container(
width: 50.0,
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(0),
child: Text(
text,
textAlign: TextAlign.center,
style: TextStyle(color: _textColor, fontWeight: FontWeight.bold),
),
),
);
});
return list;
}
}
import 'package:flutter/material.dart';
import 'package:project_five/widgets/business/adding_product_widgets/first_step.dart';
import 'package:project_five/widgets/business/adding_product_widgets/four_step.dart';
import 'package:project_five/widgets/business/adding_product_widgets/second_step.dart';
import 'package:project_five/widgets/business/adding_product_widgets/third_step.dart';
import 'package:project_five/widgets/business/custome_stepper.dart';
class AddProduct extends StatefulWidget {
const AddProduct({Key? key}) : super(key: key);
#override
State<AddProduct> createState() => _AddProductState();
}
class _AddProductState extends State<AddProduct> {
static const _stepIcons = [
Icons.add_circle,
Icons.document_scanner,
Icons.camera_alt_rounded,
Icons.check,
];
static const _titles = ['المنتج', 'تفاصيل', 'الصور', 'نشر'];
var _contnet = [
FirstStep(),
SecondStep(),
ThirdStep(),
Forth()];
var _curStep = 1;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('إضافة منتج'),
centerTitle: true,
),
persistentFooterButtons: [
Row(
children: [
Expanded(
child: ElevatedButton(
child: const Text('التالي'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(16),
),
onPressed: () => setState(() {
if (_curStep < _stepIcons.length) _curStep++;
}),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: ElevatedButton(
child: const Text('رجوع'),
style: ElevatedButton.styleFrom(
primary: Colors.white,
onPrimary: Colors.black,
padding: const EdgeInsets.all(16)),
onPressed: () => setState(() {
if (_curStep > 1) _curStep--;
}),
),
),
],
)
],
body: CustomeStepper(
icons: _stepIcons,
width: MediaQuery.of(context).size.width,
curStep: _curStep,
titles: _titles,
circleActiveColor: Colors.green,
circleInactiveColor: const Color(0xffD5D5D5),
iconActiveColor: Colors.white,
iconInactiveColor: Colors.white,
textActiveColor: Colors.green,
textInactiveColor: const Color(0xffD5D5D5),
content: _contnet,
),
);
}
}
I had the same problem, It would help to see your forms widgets. I will try my best to describe what you need to do.
Your textfields in your forms should be tied to your model class. Example: onChange: Product.title = TextField.value. and you should use initial value with your model properties, example: initialValue: Product.title. I think this way you can retain the state of the inputs in your forms.
As for the second part of your question, the Main widget that is controlling the stepper should have a state variable, such as isCompleted, on the last step you set this variable to 'true' and the main body of the stepper should be in a stack, in your stack you check if "isCompleted" ? Stepper : SummaryWidget.
How are handling Arabic titles for text fields and matching them with your class model properties?
I hope my answer can help!

DragTarget doesnt call onWillAccept with custom Draggable (Flutter)

I am trying to make Tags which are draggable text so that I can drag them to one of 2 DragTarget I have (ideally being able to move them between 3 DragTarget). Unfortunately I can't make them interact with the DragTargets as they dont even call onWillAccept(). My draggables are DragabbleTag and extends Draggable and my dragTargets are in a Stateful Widget and should accept them.
import 'package:myApp/components/draggableTag.dart';
import 'package:flutter/material.dart';
class DraggableTagTarget extends StatefulWidget {
final String title;
final int maxTagAmount;
final Color backgroundColor;
final List<DraggableTag> tagsPool;
const DraggableTagTarget(
{Key key,
this.title,
this.backgroundColor,
this.tagsPool,
this.maxTagAmount})
: super(key: key);
#override
_DraggableTagTargetState createState() => _DraggableTagTargetState();
}
class _DraggableTagTargetState extends State<DraggableTagTarget> {
String test = "Test";
#override
Widget build(BuildContext context) {
return DragTarget<DraggableTag>(onAccept: (DraggableTag value) {
setState(() {
widget.tagsPool.add(value);
test = value.label;
});
}, onWillAccept: (DraggableTag data) {
bool result =
widget.tagsPool.length <= widget.maxTagAmount ? true : false;
debugPrint("ONWillAccept: " + data.label + " = " + result.toString());
return result;
}, builder: (context, candidateData, rejectedData) {
return Container(
decoration: new BoxDecoration(
color: widget.backgroundColor,
border: Border.all(
color: Colors.black,
),
),
child: Column(
children: <Widget>[
Text(test),
Text(widget.title),
SizedBox(
height: 60,
child: Wrap(
children: widget.tagsPool,
),
),
],
),
);
});
}
}
Custom DragTarget 'DraggableTagTarget'
import 'package:flutter/material.dart';
class DraggableTag extends Draggable<String> {
final String label;
DraggableTag({Key key, this.label})
: super(
key: key,
data: label,
child: idleTag(label),
feedback: feedbackTag(label),
childWhenDragging: ghostTag(label),
);
static Widget idleTag(String label) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
child: Text(
label,
style: TextStyle(
fontSize: 16,
),
),
decoration: BoxDecoration(
color: Colors.blue,
border: Border.all(
color: Colors.black,
),
borderRadius: BorderRadius.all(Radius.circular(20)),
),
);
}
Custom Draggable 'DraggableTag'
I excluded feedbackTag() and ghostTag which shouldnt be relevant
At first my draggableTag was extending a widget but seeing some similar problem I made it into extending directly a Draggable but it didnt help
EDIT:
I am assigning ma values to draggable in a custom DialogWidget (stateful widget) in a list
class _RatingDialogState extends State<RatingDialog> {
List<DraggableTag> tagsPool = [
DraggableTag(label: "Acting"),
DraggableTag(label: "Scenario"),
DraggableTag(label: "Pace"),
DraggableTag(label: "Length"),
DraggableTag(label: "Message"),
];
List<DraggableTag> negativeTagsPool = [];
List<DraggableTag> positiveTagsPool = [];
#override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
elevation: 0,
backgroundColor: Colors.transparent,
child: contentBox(context),
);
}
contentBox(context) {
return Stack(
...
Wrap(
children: tagsPool,
),
SizedBox(height: 22),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Flexible(
child: FractionallySizedBox(
widthFactor: 0.85,
child: DraggableTagTarget(
title: "Negative",
backgroundColor: Colors.red,
tagsPool: negativeTagsPool,
maxTagAmount: 3),
),
),
Flexible(
child: FractionallySizedBox(
widthFactor: 0.85,
child: DraggableTagTarget(
title: "Positive",
backgroundColor: Colors.green,
tagsPool: positiveTagsPool,
maxTagAmount: 3),
),
),
]),
...
SOLUTION: as ikerfah explained, I didnt put the right type into <> because I was confused to what my DraggableTag class was. I made another class to contains the data Tag so that both my DragTarget and DraggableTag use this class
Draggable and DragTarget must have the same generic type, but you have Draggable<String> and DragTarget<DraggableTag>

SwitchListTile and Container or RaisedButton within ListView.builder not working properly

I have a Dialog class in which I want to show different designations that could be assigned to an employee.
In the beginning, I tried to use only a RaisedButton to select the desired designations. Within the App, the Button should change Colors. This part is found within a StatefulWidget.
I also tried a modified version, where I created a new StatefulWidget only for the Dialog part but this part did not have any effect, thus I thought to implement a SwitchListTile to do the same thing.
The SwitchListTile gets activated and deactivated although only the true value gets registered. This means that when I deactivate (swipe to left) the code does not go within the following setState:
setState(() { hEnabled[hDesignations[index].designation] = value; });
Also when the hEnabled Map gets changed within the setState method the following code does not re-run to change the color of the container:
color: hEnabled[hDesignations[index].designation] ? Colors.green : Colors.grey,
Part with the Dialog:
Widget buildChooseDesignations(
BuildContext context, List<Designation> hDesignations) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadiusDirectional.circular(8.0),
),
child: _buildDialogChild(context, hDesignations),
);
}
_buildDialogChild(BuildContext context, List<Designation> hDesignations) {
//todo: when editing an employee I need the chosen designations (have to pass a list)
Map<String, bool> hEnabled = new Map<String, bool>();
for (var i = 0; i < hDesignations.length; i++) {
hEnabled[hDesignations[i].designation] = false;
}
return Container(
height: 200.0,
//todo: width not working properly
width: 50,
child: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: hDesignations.length,
itemBuilder: (context, index) {
return Row(
children: <Widget>[
Expanded(
child: Container(
width: 10,
color: hEnabled[hDesignations[index].designation]
? Colors.green
: Colors.grey,
padding: EdgeInsets.only(left: 80),
child: Text(hDesignations[index].designation,
style: TextStyle(fontWeight: FontWeight.bold),),
),
),
Expanded(
child: SwitchListTile(
value: hEnabled[hDesignations[index].designation],
onChanged: (bool value) {
setState(() {
hEnabled[hDesignations[index].designation] =
value;
});
}),
)
],
);
}),
),
SizedBox(
height: 15.0,
),
RaisedButton(
color: Colors.blueGrey,
child: Text(
'set',
style: TextStyle(color: Colors.white),
),
onPressed: () {
//todo: save the 'newly' selected designations in a list on set click
},
)
],
),
);
}
The Dialog is called when I click on the Add + FlatButton and looks like this:
ButtonTheme(
height: 30.0,
// child: Container(),
child: FlatButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
color: Colors.blueGrey.shade200,
onPressed: () {
//todo add Dialog
// List<Designation> hList = state.designations;
showDialog(
context: context,
builder: (context) => buildChooseDesignations(
context, state.designations));
// DesignationDialog(
// designations:state.designations));
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0)),
child: Text(
'Add +',
style: TextStyle(color: Colors.black),
),
),
),
Found the problem :)
First I did re-write everything into a new StatefulWidget. This I needed since I want that my widget gets re-build after I click on the SwitchListTile to re-color my Container.
Then I had to move my hEnabled (re-named hChecked) map outside the state. The reason was that the widget would re-build all the everything including the initialization of this map, making the user's input useless.
The same applies to the RaisedButton Widget.
Here is my code:
class DesignationDialog extends StatefulWidget {
final List<Designation> designations;
final Map<String, bool> hChecked;
DesignationDialog({Key key, this.designations, this.hChecked}) : super(key: key);
#override
_DesignationDialogState createState() => _DesignationDialogState();
}
class _DesignationDialogState extends State<DesignationDialog> {
_buildDialogChild(BuildContext context, List<Designation> hDesignations) {
//todo: when editing an employee I need the chosen designations (have to pass a list)
// for (var i = 0; i < hDesignations.length; i++) {
// hChecked[hDesignations[i].designation] = false;
// }
return Container(
height: 200.0,
child: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: hDesignations.length,
itemBuilder: (context, index) {
// return ButtonTheme(
// //todo: fix the width of the buttons is not working
// minWidth: 20,
// child: RaisedButton(
// color: widget.hChecked[hDesignations[index].designation]
// ? Colors.green
// : Colors.grey,
// child: Text(hDesignations[index].designation),
// onPressed: () {
// //todo mark designation and add to an array
// setState(() {
// widget.hChecked[hDesignations[index].designation] =
// !widget
// .hChecked[hDesignations[index].designation];
// });
// },
// ),
// );
// -- With Switch
return Row(
children: <Widget>[
Expanded(
child: Container(
child: Text(hDesignations[index].designation),
width: 10,
color: widget.hChecked[hDesignations[index].designation]
? Colors.green
: Colors.grey,
)),
Expanded(
child: SwitchListTile(
value: widget.hChecked[hDesignations[index].designation],
onChanged: (bool value) {
setState(() {
widget.hChecked[hDesignations[index].designation] =
value;
});
}),
)
],
);
// -- end
}),
),
SizedBox(
height: 15.0,
),
RaisedButton(
color: Colors.blueGrey,
child: Text(
'set',
style: TextStyle(color: Colors.white),
),
onPressed: () {
//todo: save the 'newly' selected designations in a list on set click
},
)
],
),
);
}
#override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadiusDirectional.circular(8.0),
),
child: _buildDialogChild(context, widget.designations),
);
}