Flutter Stateful Widget used across Multiple Screens getting Rebuilt - flutter

ive created the below Multiselect Chip Widget its using Provider and Listening for changes to the list
the widget creates a List of Choice Chips that allows multiple choice chips to be chosen
class MultiSelectChip extends StatefulWidget {
final Function(List<String>) onSelectionChanged;
MultiSelectChip({this.onSelectionChanged});
#override
_MultiSelectChipState createState() => _MultiSelectChipState();
}
class _MultiSelectChipState extends State<MultiSelectChip> {
List<String> selected = List();
List<Clinic> clinicList = List();
#override
void didChangeDependencies() {
final list = Provider.of<ClinicProvider>(context).clinics;
final clinic = Clinic(
id: null,
name: "All Clinics",
city: null,
suburb: null,
postcode: null,
prate: null,
udarate: null,
goal: null,
uid: null);
clinicList.add(clinic);
selected.add(clinicList[0].name);
list.forEach((clinic) => clinicList.add(clinic));
super.didChangeDependencies();
}
_buildList() {
List<Widget> choices = List();
clinicList.forEach((item) {
choices.add(Padding(
padding: const EdgeInsets.only(left: 5.0, right: 5.0),
child: ChoiceChip(
key: Key("${item.name}"),
shape: selected.contains(item.name)
? RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(0),
),
)
: RoundedRectangleBorder(
side: BorderSide(
color: Color.fromRGBO(46, 54, 143, 1), width: 1.0),
borderRadius: BorderRadius.circular(0.0),
),
label: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(item.name),
),
onSelected: (value) {
setState(() {
selected.contains(item.name)
? selected.remove(item.name)
: selected.add(item.name);
widget.onSelectionChanged(selected);
});
},
selected: selected.contains(item.name),
selectedColor: Color.fromRGBO(46, 54, 143, 1),
labelStyle:
selected.contains(item.name) ? kChipActive : kChipInActive,
backgroundColor: Colors.transparent,
),
));
});
return choices;
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 8.0, top: 5.0, bottom: 5.0),
child: SizedBox(
height: 50,
width: double.infinity,
child: ListView(
scrollDirection: Axis.horizontal,
children: _buildList(),
),
),
);
}
}
when i click from this Log screen and goto the NewLog screen and Pop Back to the Log Screen
class LogScreen extends StatefulWidget {
static const String id = 'logscreen';
#override
_LogScreenState createState() => _LogScreenState();
}
class _LogScreenState extends State<LogScreen> {
MonthSelector selectedMonth;
List<String> selectedItems = List();
static DateTime now = DateTime.now();
static DateTime end = DateTime(now.year, now.month + 1, 0);
static DateTime start = DateTime(now.year, now.month, 1);
MonthSelector currentMonth = MonthSelector(
monthName: DateFormat("MMMM").format(now),
monthStart: start,
monthEnd: end);
void refreshData(MonthSelector selector) async {
await Provider.of<LogProvider>(context, listen: false)
.getLogs(selector.monthStart, selector.monthEnd);
await Provider.of<LogProvider>(context, listen: false)
.loadTreatments(selector.monthStart, selector.monthEnd);
}
#override
Widget build(BuildContext context) {
final List<LogSummary> list = Provider.of<LogProvider>(context).summary;
final List<FlSpot> chartData = Provider.of<LogProvider>(context).spots;
return Container(
color: Color.fromRGBO(246, 246, 246, 1),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
flex: 1,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 15,
),
RawMaterialButton(
onPressed: () {
Navigator.pushNamed(context, NewLogScreen.id);
},
constraints: BoxConstraints.tight(Size(60, 60)),
child: Icon(
Icons.add,
color: Color.fromRGBO(255, 255, 255, 1),
size: 30,
),
shape: CircleBorder(),
fillColor: Color.fromRGBO(46, 54, 143, 1),
padding: EdgeInsets.all(15.0),
elevation: 1,
),
SizedBox(
height: 10,
),
Text(
'Add log',
style: kAddLogLabel,
)
],
),
),
]),
list.isEmpty || chartData.isEmpty
? Expanded(
child: Center(
child: Text("No Log Data.."),
),
)
: Expanded(
child: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Container(
height: 150,
alignment: Alignment.center,
child: LineChartWidget(
list: chartData,
isDollar: true,
),
),
SizedBox(
height: 10,
),
MultiSelectChip(
onSelectionChanged: (selectedList) async {
setState(() {
selectedItems = selectedList;
});
await Provider.of<LogProvider>(context, listen: false)
.filterLogList(selectedItems);
},
),
MonthSelect(Color.fromRGBO(246, 246, 246, 1),
onMonthSelectionChanged: (selected) {
setState(() {
selectedMonth = selected;
});
selectedMonth == null
? refreshData(currentMonth)
: refreshData(selectedMonth);
}),
Padding(
padding:
const EdgeInsets.only(top: 10, left: 0, right: 0),
child: Container(
width: double.infinity,
height: 1.0,
color: kDividerColor,
),
),
what i am seeing is the Multiselect Chip has the Same List of Items redrawn/added to the list view 3 times, each time i go into the NewLog screen the list keeps growing
im currently using the same Widget across 4 diffrent screens, but for some reason when i navigate to one of the other screen the list resets and displays the orignal items and the duplicate items dissapear
what can i do to prevent this from redrawing, all the time when navigating off the screen
thanks

Have you tried specifying listen: false in Provider.of() used in didChangeDependencies()? It may solve the issue.
However, there can still be a risk. I doubt initialising something there is safe because didChangeDependencies() is called when/whenever a dependency of the State object changes as written in its document. It'd be safer to do it in initState(), or have it done outside only once and its result passed in to MultiSelectChip.

Related

Cannot remove strings from list in flutter

I have a page to select images from the gallery and add those urls in a list that will be passed to another page after popping. Everything works fine the first time the user accesses the page, however, when coming back to the Image View with an already populated list (passed as argument), whenever I try to edit/removing elements from it, the list remains the same. But the images I want to delete get removed correctly from the firebase storage.
I will attach the code I am trying to use. I am new to flutter so I will really appreciate your help.
If you have any questions about the code feel free to ask!
import 'dart:convert';
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:moneybo/utilities/dialogs/delete_dialog.dart';
import 'package:moneybo/utilities/dialogs/error_dialog.dart';
import 'package:moneybo/utilities/generics/get_arguments.dart';
class ImageView extends StatefulWidget {
const ImageView({super.key});
#override
State<ImageView> createState() => _ImageViewState();
}
class _ImageViewState extends State<ImageView> {
late final ImagePicker _picker;
late final ImageCache _cache;
List<String> imageUrls = [];
List<bool> isImageSelected = [];
List<String> imagesToDelete = [];
String imgs = "";
bool _isSelected = false;
#override
void initState() {
_picker = ImagePicker();
_cache = ImageCache();
super.initState();
}
#override
Widget build(BuildContext context) {
List<String>? newImageList;
final imageList = context.getArgument<String>();
if (imageList != null && imageList.isNotEmpty) {
newImageList = (jsonDecode(imageList) as List<dynamic>).cast<String>();
for (String url in newImageList) {
if (!imageUrls.contains(url)) {
imageUrls.add(url);
}
}
imgs = jsonEncode(imageUrls);
for (String element in imageUrls) {
isImageSelected.add(false);
}
}
return GestureDetector(
onTap: () {
List<bool> newIsImageSelected = [];
for (String element in imageUrls) {
newIsImageSelected.add(false);
}
setState(() {
_isSelected = false;
isImageSelected = newIsImageSelected;
imagesToDelete = [];
});
print(imageUrls);
// print(imgs);
},
child: Scaffold(
appBar: AppBar(
centerTitle: true,
toolbarHeight: 73,
leading: Padding(
padding: const EdgeInsets.only(top: 25, left: 5),
child: TextButton(
child: const Text(
"OK",
style: TextStyle(fontSize: 18, color: Colors.white),
),
onPressed: () => Navigator.pop(context, imgs),
),
),
actions: [
Padding(
padding: const EdgeInsets.only(right: 20, top: 20),
child: isImageSelected.contains(true)
? IconButton(
onPressed: () async {
final shouldDelete = await showDeleteDialog(
context, "Delete this image(s)?");
if (shouldDelete) {
for (String deleteImage in imagesToDelete) {
imageUrls.removeWhere((image) =>
image.hashCode == deleteImage.hashCode);
await FirebaseStorage.instance
.refFromURL(deleteImage)
.delete();
}
imgs = jsonEncode(imageUrls);
List<bool> newIsImageSelected = [];
for (String element in imageUrls) {
newIsImageSelected.add(false);
}
_cache.clear();
_cache.clearLiveImages();
setState(() {
isImageSelected = newIsImageSelected;
imagesToDelete = [];
});
}
},
icon: SizedBox(
height: 25,
child: Image.asset(
"lib/icons/bin.png",
color: Colors.white,
)))
: IconButton(
icon: const Icon(Icons.add_a_photo_rounded),
onPressed: () async {
List<XFile>? images = await _picker.pickMultiImage();
String uniqueFileName =
DateTime.now().microsecondsSinceEpoch.toString();
Reference referenceRoot =
FirebaseStorage.instance.ref();
Reference referenceDirImages =
referenceRoot.child("images");
try {
for (XFile image in images) {
uniqueFileName =
(int.parse(uniqueFileName) + 1).toString();
Reference referenceImageToUpload =
referenceDirImages.child(uniqueFileName);
await referenceImageToUpload
.putFile(File(image.path));
String imageUrl =
await referenceImageToUpload.getDownloadURL();
imageUrls.add(imageUrl);
isImageSelected.add(false);
}
} catch (error) {
if (mounted) {
showErrorDialog(context, "$error");
}
}
imgs = jsonEncode(imageUrls);
setState(() {});
},
),
),
],
title: const Padding(
padding: EdgeInsets.only(top: 30.0),
child: Text(
"Add images",
style: TextStyle(fontSize: 16),
),
),
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: <Color>[
Color.fromRGBO(24, 92, 92, 1),
Color.fromRGBO(33, 108, 108, 1),
Color.fromRGBO(40, 121, 121, 1),
Color.fromRGBO(48, 136, 136, 1),
Color.fromRGBO(50, 139, 139, 1),
Color.fromRGBO(54, 143, 143, 1),
Color.fromRGBO(57, 145, 145, 1),
]),
),
),
),
body: imageUrls.isNotEmpty
? Padding(
padding: const EdgeInsets.only(top: 20, left: 8, right: 8),
child: GridView.builder(
itemCount: imageUrls.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: imageUrls.length > 1 ? 2 : 1,
mainAxisSpacing: imageUrls.isNotEmpty ? 8 : 0,
crossAxisSpacing: imageUrls.isNotEmpty ? 8 : 0,
),
itemBuilder: (context, index) {
return GestureDetector(
onLongPress: () {
setState(() {
_isSelected = true;
});
},
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: _isSelected
? Colors.green
: const Color.fromRGBO(11, 68, 68, 1),
width: _isSelected ? 4 : 2),
borderRadius:
const BorderRadius.all(Radius.circular(20))),
child: Stack(
children: [
Center(
child: Image.network(
imageUrls[index],
fit: BoxFit.contain,
),
),
_isSelected
? Align(
alignment: Alignment.topRight,
child: Transform.scale(
scale: 1.3,
child: Checkbox(
side: const BorderSide(
width: 2,
color: Color.fromRGBO(
11, 68, 68, 1)),
shape: const CircleBorder(),
value: isImageSelected[index],
onChanged: (bool? value) {
setState(() {
isImageSelected[index] = value!;
});
if (isImageSelected[index]) {
if (imagesToDelete.isNotEmpty) {
imagesToDelete.insert(
index, imageUrls[index]);
} else {
imagesToDelete
.add(imageUrls[index]);
}
} else if (!isImageSelected[
index] &&
imagesToDelete.contains(
imageUrls[index])) {
imagesToDelete
.remove(imageUrls[index]);
} else {
return;
}
print(imagesToDelete);
}),
),
)
: const SizedBox(),
],
),
),
);
},
),
)
: Padding(
padding: const EdgeInsets.only(bottom: 150),
child: Center(
child: SizedBox(
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(
Icons.image_not_supported_outlined,
size: 150,
color: Color.fromRGBO(168, 168, 168, 1),
),
SizedBox(height: 25),
Text(
"No images yet",
style: TextStyle(
color: Color.fromRGBO(168, 168, 168, 1),
fontSize: 25,
),
)
]),
)),
),
),
);
}
}

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.

How to display the saved state of a button when the page opens?

I have three buttons. The maximum that I can select (activate) is only one button. When switching buttons, I have activated should be true, and not activated - false. I write these values ​​to SharedPreferences for each button, store true or false. When I open the pages all the buttons are gray out (they are not selected). I need to save the button state that it was selected and display it when the page is opened. For example, I just need if the variable isVoltageAC = true, then the AC button will immediately turn purple when the page is opened. How to do it?
enum VoltageMode {
ac,
dc,
all,
}
class FilterDialog extends StatefulWidget {
const FilterDialog({
Key? key,
}) : super(key: key);
#override
State<FilterDialog> createState() => _FilterDialogState();
}
class _FilterDialogState extends State<FilterDialog> {
VoltageMode? selectedMode;
#override
Widget build(BuildContext context) {
return BlocBuilder<MapPreferencesCubit, MapPreferencesState>(
builder: (context, statePreferences) {
final MapPreferencesCubit mapPreferencesCubit =
BlocProvider.of<MapPreferencesCubit>(context);
if (statePreferences is MapPreferencesInitial) {
mapPreferencesCubit.getPreferences();
}
if (statePreferences is MapPreferencesLoaded) {
return BlocBuilder<MapfilterCubit, MapFilterState>(
builder: (context, stateFilter) {
final MapfilterCubit mapFilterCubit =
BlocProvider.of<MapfilterCubit>(context);
if (stateFilter is MapFilterInitial) {
mapFilterCubit.getFilter();
}
if (stateFilter is MapFilterLoaded) {
bool isVoltageAC = stateFilter.mapFilter.voltagePowerAC;
bool isVoltageDC = stateFilter.mapFilter.voltagePowerDC;
bool isVoltageAll = stateFilter.mapFilter.voltagePowerAll;
return SingleChildScrollView(
child: Dialog(
insetPadding: const EdgeInsets.only(
top: 121, left: 24, right: 24, bottom: 60),
child: Container(
decoration: const BoxDecoration(
color: constants.Colors.greyDark,
borderRadius: BorderRadius.all(Radius.circular(24)),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 26, 0, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [,
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 21),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () => setState(() {
selectedMode = VoltageMode.ac;
}),
child: _buttonVoltage(
'AC', selectedMode == VoltageMode.ac),
),
const SizedBox(width: 16),
GestureDetector(
onTap: () => setState(() {
selectedMode = VoltageMode.dc
}),
child: _buttonVoltage(
'DC', selectedMode == VoltageMode.dc),
),
const SizedBox(width: 16),
GestureDetector(
onTap: () => setState(() {
selectedMode = VoltageMode.all;
}),
child: _buttonVoltage(
'All', selectedMode == VoltageMode.all),
),
],
),
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 21),
child: DefaultButtonGlow(
text: 'Done',
onPressed: () {
Navigator.pop(context);;
mapFilterCubit
.setFilter(
MapFilter(
voltagePowerAC:
selectedMode == VoltageMode.ac,
voltagePowerDC:
selectedMode == VoltageMode.dc,
voltagePowerAll:
selectedMode == VoltageMode.all,
),
)
},
),
Widget _buttonVoltage(String nameButton, bool isActive) => Container(
padding: const EdgeInsets.symmetric(vertical: 11),
height: 40,
width: 87,
decoration: BoxDecoration(
color: isActive
? constants.Colors.purpleMain
: constants.Colors.white.withOpacity(0.15),
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: isActive ? Colors.transparent : constants.Colors.greyDark,
),
boxShadow: [
BoxShadow(
color: isActive
? constants.Colors.purpleMain.withOpacity(0.34)
: Colors.transparent,
blurRadius: 10,
spreadRadius: 2,
offset: const Offset(0.0, 1.0)),
],
),
alignment: Alignment.center,
child:
Text(nameButton, style: constants.Styles.smallBoldTextStyleWhite),
);
cubit
Future setFilter(MapFilter mapFilter) async {
await _repository.setFilter(mapFilter: mapFilter);
final MapFilter? filter = await _repository.getFilter();
emit(MapFilterLoaded(filter!));
return filter;}
sharedpreferences
Future setFilter({required MapFilter mapFilter}) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(_filterName, jsonEncode(mapFilter.toJson()));
}
you can read this values from SharedPreferences in initState of page. In this way your default value is ready when page loaded.
then make everything after SingleChildScrollView in separate widget like this:
Widget _buildBody(){
return SingleChildScrollView(
child: Dialog(
...
),
);
}
and pass this widget in your bloc builder after all if statement by default.
then do this:
void initState() {
super.initState();
final SharedPreferences prefs = await SharedPreferences.getInstance();
var result = prefs.readData(_filterName);
if (result != null) {
MapFilter mapFilter = jsonDecode(mapFilter.fromJson(result));
if (mapFilter.voltagePowerAC){
selectedMode = VoltageMode.ac;
}else if (mapFilter.voltagePowerDC){
selectedMode = VoltageMode.dc;
} else {
selectedMode = VoltageMode.all;
}
}
}

Rendering Filtered List in Flutter

I'm having trouble displaying a filtered list in my widget. It works up to the point of printing the filtered data in the list as per the query that is passed but not when that exact data needs to be displayed. I believe I will have to update the list with the filtered data every time I type in a query but I just cannot figure out how and where I need to use setState to update that. My code and the outputs are as follows:
Initially, the entire list gets rendered but the moment I type in a query string, the list is supposed to get modified with only the data that matched the query. This is not something that's happening at the moment. The list tends to remain as it is.
However, when I print the filtered data, it seems to work just fine(_searchResult printed in the searchData method below).
[
{product_id: 8, restaurant_name: Mocambo, restaurant_id: 6, product_name: Kaju Paneer, product_description: Tasty yummy paneer gravy dish, product_image: /public/assets/product/lgml5L03-19-41.jpg, product_selling_price: 320},
{product_id: 5, restaurant_name: City Club, restaurant_id: 1, product_name: Palak Paneer, product_description: Tasty silky gravy with goodness of palak, product_image: /public/assets/product/C6pGz101-42-17.jpg, product_selling_price: 180},
{product_id: 4, restaurant_name: City Club, restaurant_id: 1, product_name: Shahi Paneer, product_description: Tasty Paneer main course dish, product_image: /public/assets/product/vgI1dR01-29-18.jpg, product_selling_price: 240}
]
The code:
The method that filters. (Please note that the filtering is performed after the data is fetched from the server. For my convenience, I decided to convert it into a list)
class PopularDishesProvider with ChangeNotifier {
Map<String, dynamic> _dishes = {};
final List<dynamic> _searchDish = [];
List<dynamic> _searchResult = [];
List<dynamic> get searchDish {
return [..._searchDish];
}
List<dynamic> get searchResult {
return [..._searchResult];
}
Future<void> searchData(String query) async {
final url = Uri.parse(baseUrl + 'api/all_products');
final response = await http.get(url);
PopularDishes popularDishes = popularDishesFromJson(response.body); //This method converts the response into Dart model
_dishes = popularDishes.toJson();
_dishes['data'].forEach((value) => _searchDish.add(value));
_searchResult = _searchDish.where((element) {
final name = element['product_name'].toLowerCase();
final searchQuery = query.toLowerCase();
return name.contains(searchQuery);
}).toList();
print(_searchResult);
notifyListeners();
}
}
The widget where this is supposed to be rendered:
class SearchState extends State<Search> {
final _controller = TextEditingController();
bool value = true;
String query = '';
List<dynamic> search = [];
PopularDishesProvider popular = PopularDishesProvider();
#override
void initState() { //This is to make the API Call for the first time
// TODO: implement initState
Provider.of<PopularDishesProvider>(context, listen: false)
.searchData('');
});
super.initState();
}
#override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
final textScale = MediaQuery.of(context).textScaleFactor * 1.2;
final searchProvider = Provider.of<PopularDishesProvider>(context).searchResult;
PopularDishesProvider popular = PopularDishesProvider();
// TODO: implement build
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
elevation: 5,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
// backgroundColor: Colors.green,
titleSpacing: 0,
toolbarHeight: 100,
title: Column(
children: [
Container(
width: double.infinity,
height: 40,
.......
.......
.......
),
Stack(
children: [
Container(
height: 60,
width: double.infinity,
// color: Colors.red,
padding: const EdgeInsets.only(top: 8, left: 2),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Icon(
Icons.search,
size: 30,
color: Colors.grey,
),
Expanded(
child: Center(
child: Container(
margin:
const EdgeInsets.only(bottom: 6, right: 4),
padding: const EdgeInsets.only(left: 6),
height: 45,
width: width * 0.7,
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(
Radius.circular(14)),
border:
Border.all(color: Colors.grey, width: 2)),
child: Row(
children: [
Flexible(
flex: 9,
fit: FlexFit.tight,
child: Center(
child: TextField(
controller: _controller,
onChanged: (value) async {
setState(() {
query = value;
});
await popular.searchData(value);
},
autofocus: true,
cursorColor: Colors.grey,
style: const TextStyle(
color: Colors.grey, fontSize: 18),
decoration: const InputDecoration(
border: InputBorder.none,
hintText:
'Search By Restaurant or Food',
hintStyle:
TextStyle(color: Colors.grey),
),
),
)),
Flexible(
flex: 1,
fit: FlexFit.tight,
child: InkWell(
onTap: () => Navigator.of(context).pop(),
child: const Icon(Icons.close,
color: Colors.grey),
),
)
],
),
),
),
),
],
),
),
],
)
],
)),
body: Column(
children: [
Expanded(
child: Container(
width: double.infinity,
color: Colors.red,
child: ListView.builder(
itemBuilder: (context, index) => ListTile(
title: Text(searchProvider [index]['product_name'])),
itemCount: searchProvider.length,
),
)
)
],
),
);
}
}
Can someone please help out?

GlobalKey<FormState>().currentState.save() is falling when I submit a form in Flutter

Using bloc from rxdart: ^0.24.1
I am trying to save object on mysql. The first try the object get saved succefully, the second try, with a new object, it falling on formKey.currentState.save(). I am using GlobalKey<FormState>() in order to validate the form with Stream
My code is
class DetailGamePage extends StatefulWidget {
#override
_DetailGameState createState() => _DetailGameState();
}
class _DetailGameState extends State<DetailGamePage> {
final formKey = GlobalKey<FormState>();
GameBloc gameBloc;
#override
void didChangeDependencies() {
super.didChangeDependencies();
if (gameBloc == null) {
gameBloc = Provider.gameBloc(context);
}
}
#override
Widget build(BuildContext context) {
Game _game = ModalRoute.of(context).settings.arguments;
if (_game == null) {
_game = Game(
color: "#000000",
description: "",
env: "",
isBuyIt: false,
isOnBacklog: false);
}
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
backgroundColor: Colors.white,
title: Text(
"Add Game",
style: TextStyle(color: Colors.black),
),
actions: [
FlatButton(
onPressed: () {
if (formKey.currentState.validate()) {
formKey.currentState.save();
Fluttertoast.showToast(msg: "Game saved");
setState(() {
gameBloc.saveOrUpdate(_game, gameBloc.name,
gameBloc.description, "listGame");
});
Navigator.pushReplacementNamed(context, "home");
}
},
child: Text(
(StringUtils.isNullOrEmpty(_game.id)) ? "Add" : "Update",
style: TextStyle(color: HexColor(_game.color), fontSize: 20),
))
],
),
body: Form(
key: formKey,
child: Stack(children: <Widget>[
_createBackground(context, _game),
_createFormGame(context, _game, gameBloc)
]),
));
}
Widget _createBackground(BuildContext context, Game game) {
final size = MediaQuery.of(context).size;
final gradientTop = Container(
height: size.height, //* 0.4,
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: <Color>[HexColor(game.color), Colors.white])),
);
final circule = Container(
width: 100.0,
height: 100.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100.0),
color: Color.fromRGBO(255, 255, 255, 0.1)),
);
return Stack(
children: <Widget>[
gradientTop,
Positioned(
child: circule,
top: 90,
left: 50,
),
Positioned(
child: circule,
top: -40,
right: -30,
),
Container(
padding: EdgeInsets.only(top: 80),
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
width: double.infinity,
),
],
),
)
],
);
}
Widget _createFormGame(BuildContext context, Game game, GameBloc gameBloc) {
final size = MediaQuery.of(context).size;
return SingleChildScrollView(
child: Column(
children: <Widget>[
SafeArea(
child: Container(
height: 80.0,
)),
Container(
width: size.width * 0.85,
padding: EdgeInsets.symmetric(vertical: 50.0),
margin: EdgeInsets.symmetric(vertical: 30.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5.0),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.black26,
blurRadius: 3.0,
offset: Offset(0.0, 5.0),
spreadRadius: 3.0)
]),
child: Column(
children: <Widget>[
Text("Foto", style: TextStyle(fontSize: 20.0)),
SizedBox(
height: 50.0,
),
_createNameImput(gameBloc, game),
_createDescriptionImput(gameBloc, game),
Divider(
height: 30,
color: HexColor(game.color),
indent: 30,
endIndent: 20,
),
_createWasGameImput(gameBloc, game),
Divider(
height: 30,
color: HexColor(game.color),
indent: 30,
endIndent: 20,
),
_createToTheBacklogImput(gameBloc, game),
SizedBox(height: 60),
_createDeleteButton(gameBloc, game),
SizedBox(height: 60),
],
))
],
),
);
}
#override
void dispose() {
gameBloc?.dispose();
super.dispose();
}
Widget _createWasGameImput(GameBloc gameBloc, Game game) {
return StreamBuilder(
builder: (BuildContext context, AsyncSnapshot snapshot) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: SwitchListTile(
activeColor: HexColor(game.color),
title: Text("Do you have it?"),
value: game.isBuyIt,
onChanged: (bool value) {
setState(() {
game.isBuyIt = value;
});
},
secondary: IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: null,
color: HexColor(game.color),
),
));
},
);
}
Widget _createToTheBacklogImput(GameBloc gameBloc, Game game) {
return StreamBuilder(
builder: (BuildContext context, AsyncSnapshot snapshot) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: SwitchListTile(
activeColor: HexColor(game.color),
title: Text("To the backlog?"),
value: game.isOnBacklog,
onChanged: (bool value) {
setState(() {
game.isOnBacklog = true;
});
},
secondary: IconButton(
icon: Icon(Icons.list),
onPressed: null,
color: HexColor(game.color),
),
));
},
);
}
Widget _createNameImput(GameBloc gamebloc, Game game) {
return Column(children: [
Container(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: TextFormField(
textCapitalization: TextCapitalization.sentences,
initialValue: game.name,
onSaved: (value) {
gameBloc.setName(value);
},
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: "Name",
icon: Icon(
Icons.games,
color: HexColor(game.color),
)),
),
),
Divider(
height: 30,
color: HexColor(game.color),
indent: 30,
endIndent: 20,
),
]);
}
Widget _createDescriptionImput(GameBloc gameBloc, Game game) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: TextFormField(
textCapitalization: TextCapitalization.sentences,
initialValue: game.description,
onSaved: (value) {
gameBloc.setDescription(value);
},
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: "Description",
icon: Icon(
Icons.description,
color: HexColor(game.color),
)),
),
);
}
Widget _createDeleteButton(GameBloc gameBloc, Game game) {
if (StringUtils.isNotNullOrEmpty(game.id)) {
return FlatButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text("Do you wan to remove the game"),
actions: <Widget>[
FlatButton(
onPressed: () {
setState(() {
gameBloc.remove(game, "listGame");
});
Navigator.pop(context);
Navigator.pop(context);
},
child: Text("Yes")),
FlatButton(
onPressed: () => Navigator.of(context).pop(),
child: Text("No"))
],
);
});
},
child: Text("Remove Game"));
} else {
return Container();
}
}
}
This is the bloc
class GameBloc extends Validators {
//Controller
final _allDataGames = BehaviorSubject<List<Game>>();
final _descriptionController = BehaviorSubject<String>();
final _nameController = BehaviorSubject<String>();
final _allMyListGamesByNameController = BehaviorSubject<List<Game>>();
//Services
GameService gameService = GameService();
//get Data from streams
Stream<List<Game>> get allGameData => _allDataGames.stream;
Stream<List<Game>> get allGameByNameList =>
_allMyListGamesByNameController.stream;
Stream<String> get getDescriptionStream =>
_descriptionController.stream.transform(validateDescription);
Stream<String> get getNameStream =>
_nameController.stream.transform(validName);
//Observable
Stream<bool> get validateDescriptionStream =>
Rx.combineLatest([getDescriptionStream], (description) => true);
Stream<bool> get validateNameStream =>
Rx.combineLatest([getNameStream], (name) => true);
//Set Stream
Function(String) get setDescription => _descriptionController.sink.add;
Function(String) get setName => _nameController.sink.add;
//Get Stream
//From repo
void allGames() async {
List<Game> games = await gameService.getAllDataGames();
_allDataGames.sink.add(games);
}
//From my setting
void allMyListGamesByName(String listName) async {
List<Game> games = await gameService.allMyListGamesByName(listName);
_allMyListGamesByNameController.sink.add(games);
}
void saveOrUpdate(
Game game, String name, String description, String listGame) {
game.name = name;
game.description = description;
if (StringUtils.isNullOrEmpty(game.id)) {
game.id = Uuid().v1();
gameService.add(game, listGame);
} else {
gameService.update(game);
}
}
void remove(Game game, String listGame) {
gameService.remove(game, listGame);
}
//Get Lastest stream value
String get name => _nameController.value;
String get description => _descriptionController.value;
dispose() {
_descriptionController?.close();
_allMyListGamesByNameController?.close();
_allDataGames?.close();
_nameController?.close();
}
}
The provider:
class Provider extends InheritedWidget {
static Provider _imstance;
final _gameBloc = GameBloc();
factory Provider({Key key, Widget child}) {
if (_imstance == null) {
_imstance = new Provider._internal(key: key, child: child);
}
return _imstance;
}
Provider._internal({Key key, Widget child}) : super(key: key, child: child);
static GameBloc gameBloc(BuildContext context) {
return (context.inheritFromWidgetOfExactType(Provider) as Provider)
._gameBloc;
}
#override
bool updateShouldNotify(InheritedWidget oldWidget) {
return true;
}
}
The error is:
════════ Exception caught by gesture ═══════════════════════════════════════════
Bad state: Cannot add new events after calling close
When I evaluate formKey.currentState.save(); I got:
formKey.currentState.save()
Unhandled exception:
Bad state: Cannot add new events after calling close
#0 _BroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:249:24)
#1 Subject._add (package:rxdart/src/subjects/subject.dart:141:17)
#2 Subject.add (package:rxdart/src/subjects/subject.dart:135:5)
#3 _StreamSinkWrapper.add (package:rxdart/src/subjects/subject.dart:167:13)
I was reading about this error, it mention the error is on Bloc singleston scope or dispose method.
What is happen?
When you navigate to home with Navigator.pushReplacementNamed(context, "home"), the _DetailGamePage<State> is being disposed, calling gameBloc?.dispose. This leaves _gameBloc instantiated with all streams closed.
As you are using a Singleton Provider, when you navigate back to DetailGamePage, your save is trying to write to the closed streams.
What you need to do is move the closure of the streams farther up the widget tree so as not to close them before you are done with them, perhaps at the app level OR re-instantiate _gameBloc if the streams are closed, loading the data from the repo again.