how to get selections from multi_select_flutter? - flutter

has to be something simple I'm not getting but have been struggling on this for way too long. If anybody can help me out I would be appreciative. I believe it has to do with some kind of type issues as when I make selections I have a print statement that then prints out what I'm getting back:
[Instance of 'MultiSelectItem', Instance of 'Analysis', Instance of 'Analysis']
Not sure how to convert the above to a List of Analysis and not able to carry out per the example for the package:
MultiSelectDialogField(
items: _animals.map((e) => MultiSelectItem(e, e.name)).toList(),
listType: MultiSelectListType.CHIP,
onConfirm: (values) {
_selectedAnimals = values;
},
),
where I also have to use a 'cast' in my code. My attempt:
MultiSelectDialogField(
items: _analyses.map((analysis) => MultiSelectItem<Analysis>(analysis, analysis.name)).toList(),
initialValue: outwardsData.outwards[widget.index].lossFeed
.map((analysis) => MultiSelectItem<Analysis>(analysis, analysis.name))
.toList(),
title: Text(
"Loss Feeds:",
style: TextStyle(color: Colors.black),
),
selectedColor: kConvexGreen,
unselectedColor: kConvexLightGreen,
backgroundColor: kConvexGreen,
decoration: BoxDecoration(
color: kConvexGreen.withOpacity(0.1),
borderRadius: BorderRadius.all(Radius.circular(5)),
border: Border.all(
color: kConvexGreen,
width: 2,
),
),
confirmText: Text(
'Submit',
style: TextStyle(color: Colors.white),
),
cancelText: Text(
'Cancel',
style: TextStyle(color: Colors.white),
),
searchable: true,
buttonText: Text("Loss Feeds"),
onSelectionChanged: (results) {
**print(results)**;
},
onConfirm: (results) {
// this is different than what example shows; without cast it errors
// "A value of type 'List<Object?>' can't be assigned to a variable of type 'List<Analysis>'". (Documentation)
_selectedAnalyses = results.cast();
},
chipDisplay: MultiSelectChipDisplay(
chipColor: kConvexGreen,
textStyle: TextStyle(color: Colors.white),
onTap: (value) {
setState(() {
_selectedAnalyses.remove(value);
// crashes here even though both are of same type List<Analyses> (theoretically)
// this is just here for testing purposes as am through many iterations trying to get
// data into lossFeed.
outwardsData.outwards[widget.index].lossFeed =
_selectedAnalyses;
});
},
),
),

I'm sure a more experienced flutter person will understand this (maybe) but I found that I couldn't just have the initial values come from the same list type used for the item (List< Analysis> _analyses) but I actually had to map it to use the same items data (_analyses).
initialValue: outwardsData.outwards[widget.index].lossFeed.map((analysis) => _analyses[analysis.id - 1]).toList()
Had other problems with this widget such as I found I couldn't map the results from onConfirm directly to List but instead had to do the following:
_rData.lossFeed = results.toList().cast<Analysis>()
as the data came back as List< dynamic>.
Couldn't find great examples online and trust experience will be the cure-all at some point.

Related

How to save DropdownButtonFormField value to Firebase real-time database?

I'm using firebase real-time database and I have a form where the user adds the information to the database using it, but I'm stuck with the DropdownButtonFormField, how can I store the value in my database when the form button is pressed?
I used to use the controller when it was TextFormField, but now, I don't know what to do
DropdownButtonFormField(
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(20.0)),
borderSide:
BorderSide(width: 2, color: appColor),
),
labelText: 'Location',
labelStyle: TextStyle(
fontSize: 20, color: Colors.black)),
isExpanded: true,
// Initial Value
value: selectedLocation,
icon: const Icon(
Icons.keyboard_arrow_down,
color: appColor,
),
// Array list of items
items: Locations.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items),
);
}).toList(),
// After selecting the desired option,it will
// change button value to selected value
onChanged: (String? newLocation) {
setState(() {
selectedLocation = newLocation!;
});
},
),
you get the selectedLocation value and pass that to firebase method. print selectedLocation in the onChange method then when ever you click item in dropdown, the selectedLocation will change.
DatabaseReference ref = FirebaseDatabase.instance.ref("users/123");
await ref.set({
"selectedLocation": selectedLocation ,
});

Cannot update DropdownButtonFormField field value in flutter with getx obs

I am using getx obs with fluter and the below is json response.
[{"id":1,"designation":"Deputy General Manager"},{"id":2,"designation":"Executive Director, Technical Operations","designation_short_code":"ED, TO"},{"id":3,"designation":"Manager","designation_short_code":"M"},{"id":4,"designation":"Sr. Manager","designation_short_code":"Sr. M"}]
In controller I am using--
var listData = List<dynamic>.empty(growable: true).obs;
var designation = 1.obs;
void setDesignation(int value) {
designation.value = value;
}
I am getting the above json response based on api call under listData.
In UI I am using the below code..
Obx(() => DropdownButtonFormField<dynamic>(
decoration: InputDecoration(
hintText: 'Designation',
labelText: 'Select Designation',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
filled: true,
fillColor: Colors.white,
errorStyle: TextStyle(color: Colors.yellow),
),
hint: Text(
'Select Designation',
),
onChanged: (selectedValue) {
designation_controller
.setDesignation(selectedValue);
},
value:
designation_controller.designation.value.toInt(),
items: designation_controller.listData.map((map) {
return DropdownMenuItem(
child: Text(map['designation']),
value: map['id'],
);
}).toList(),
)),
My problem is whenever I select designation it is not updating though my api end point is hitting with 200 response.
Can anyone help me please.
Thanks in advnace.
I have fixed problem. My problem was in the below code
updateData(
controller.userData[0]['id'],
controller.designationEdittingTextController.text
)
I have changed controller.designationEdittingTextController.text to controller.designationEdit.value as below
updateData(
controller.userData[0]['id'],
controller.designationEdit.value
)
Thanks

How to pass multiple parameters to a function calling onTap of SfCalender in Flutter?

I am using SfCalender and want to pass one more parameter to a callBack of onTap
SfCalendar(
dataSource: _getDataSource(snapshot.data.data),
view: CalendarView.month,
showNavigationArrow: true,
monthViewSettings: MonthViewSettings(
showAgenda: true,
agendaStyle: AgendaStyle(
backgroundColor: Colors.transparent,
appointmentTextStyle: TextStyle(
color: Colors.white, fontSize: 13, fontStyle: FontStyle.italic),
dateTextStyle: TextStyle(
color: primaryColor, fontSize: 13, fontStyle: FontStyle.italic),
),
),
controller: _calendarController,
onTap: _openForm(array),
)
_openForm(CalendarTapDetails details) {
//code
}
Currently if I dont pass any argument to _openForm, CalenderDetails details have the values but I want to pass one array along with CalenderDetails details. How can I do that?
I don't know the SfCalendar library (and it is closed source), but I think you are trying to do that:
onTap: (details) => _openForm(details, array);
// ...
_openForm(CalendarTapDetails details, List myArray) {
// code
}

Flutter Network Image, loading the same image

I'm trying to make an app that you enter an image size as string in an input field then it gives you a random image from https://picsum.photos/,
the problem is that if I put a string lets say '200',
the app load an image, when I use '200' another time the app give me the same image until I reload the whole app.
If there is a way to make the app load different image every time I press the button.
here is some code I used:
FadeInImage.assetNetwork(
placeholder: 'lib/img/loading.gif',
image: 'https://picsum.photos/${globals.imageSize}',
),
Container(
width: 100,
child: TextField(
decoration: InputDecoration(
hintText: 'Size:',
),
onChanged: (String str) {
globals.imageSize = str;
},
),
),
RaisedButton(
child: Text(
'Search',
style: TextStyle(color: Colors.white, fontSize: 15),
),
color: Colors.lightBlueAccent,
onPressed: () {
Navigator.of(context).pushNamed('search');
},
),
Use setState to update the value.
onChanged: (String str) {
setState(() {
str = globals.imageSize;
});
},

text with \n and unicode literals saved in mysql do not work when displayed

I store a text string with \n and unicode literals like \u2022 in mysql, then retrieve it with http api call on flutter. When displaying it with Text widget, these escaped symbles do not show as expected. When I directly pass the string , it works. Could anyone help me out?
child: Column(
children: <Widget>[
Text(prompt.prompt_body, //This variable is from http call which does not work
textAlign: TextAlign.left,
style:TextStyle(
color: Colors.black,
fontSize: 13,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic
)),
Divider(),
Text("You live in a room in college which you share with another student.However, there are many problems with this arrangement and you find it very difficult to work.\n\nWrite a letter to the accommodation officer at the college. In the letter,\n\n \u2022 describe the situation\n \u2022 explain your problems and why it is difficult to work\n \u2022 say what kind of accommodation you would prefer", //this part works
textAlign: TextAlign.left,
style:TextStyle(
color: Colors.black,
fontSize: 13,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic
))
],
),
emulator screenshot
In response to Gunter's query, I add the following code on api call:
class PromptModel {
int id;
String prompt_body;
String prompt_image;
PromptModel(this.id, this.prompt_body, this.prompt_image);
PromptModel.fromJson(Map<String, dynamic> parsedJson) {
id = parsedJson['id'];
prompt_body = parsedJson['prompt_body'];
prompt_image = parsedJson['prompt_image'];
}
}
....
class PromptListPageState extends State<PromptListPage> {
int counter = 0;
List<PromptModel> prompts = [];
void fetchImage() async {
counter++;
var response =
await get('http://10.0.2.2:8080/TestPrompt');
var promptModel = PromptModel.fromJson(json.decode(response.body));
setState(() {
prompts.add(promptModel);
});
}
The following is the response of the api call:
{"id":1,"prompt_body":"You live in a room in college which you share with another student.However, there are many problems with this arrangement and you find it very difficult to work.\\n\\nWrite a letter to the accommodation officer at the college. In the letter,\\n\\n \\u2022 describe the situation\\n \\u2022 explain your problems and why it is difficult to work\\n \\u2022 say what kind of accommodation you would prefer","prompt_image":"http://10.0.2.2:8080/test.jpg"}
I solved the problem by inputting the string from flutter using TextFormField. directly inserting the text on database side is tricky. The code is as below:
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: Form(
key: formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
controller: myController,
maxLines: 5,
validator: (val) =>
(val == null || val.isEmpty) ? "请输入商品名称" : null,
decoration: const InputDecoration(
//icon: Icon(Icons.person),
hintText: 'add the prompt here:',
labelText: 'Prompt content',
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.teal)),
),
onSaved: (val) => this.content = val,
),
new Container(
margin: const EdgeInsets.only(top: 10.0),
child: new RaisedButton(
onPressed: _save,
child: new Text('Save'),
),
)
]),
),
appBar: AppBar(
title: Text('Add Essay Prompt'),
),
),
);
}
}