How to use setstate in the Void function? - flutter

I'm still new to Flutter. I want to ask why I can't use setState () in void function
here's my code: my goal is that the slider can be responsive. Previous problem I am still confused in using the SetState void function. so first of all when pressing the filter button a pop up window will appear where will display the contents of the filter that is several categories, then in the price category there is a function to display the slider. and my slider is like just an image and can't be changed. but the value has changed
void _onButtonPressed1() {
//Function for Button Press "Sort"
showModalBottomSheet(
context: context,
builder: (context) {
return Container(
color: Colors.black,
height: 500,
child: Container(
child: column1(),
decoration: BoxDecoration(
color: Colors.cyan[400],
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(30),
topRight: const Radius.circular(30),
)),
),
);
});}
new Expanded(
child: new Padding(
//padding overall filter include text&square
padding: EdgeInsets.fromLTRB(15, 0, 20, 0),
child: new Card(
color: Colors.transparent,
shape: const RoundedRectangleBorder(
side: BorderSide(
color: Colors.cyanAccent,
),
borderRadius: BorderRadius.all(Radius.circular(6.0)),
),
child: new RaisedButton(
child: new Row(children: <Widget>[
new Padding(
padding: EdgeInsets.fromLTRB(5.0, 0, 40, 0),
child: new Icon(Icons.format_align_left, color: Colors.cyanAccent),
),
new Text(
'Filter',
style: new TextStyle(
fontSize: 13,
color: Colors.cyanAccent,
),
),
]),
color: Colors.black,
padding: EdgeInsets.fromLTRB(1, 1, 1, 1),
onPressed: () => {
showModalBottomSheet(
context: context,
builder: (context) {
return Container(
color: Colors.black,
height: 350,
child: Container(
// child: column(),
child: Wrap(
//dropdown button
children: <Widget>[
ListView.builder(
shrinkWrap: true,
itemCount: 3,
itemBuilder: (context, index) {
if (index < 2) {
final sort = _sort[index];
return ExpansionTile(
title: ListTile(
title: Text(
sort.category,
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
),
children: <Widget>[ListTile(title: sort.item)],
);
} else {
return ExpansionTile(
title: ListTile(
title: Text(
'By Price',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
)),
children: <Widget>[
new RangeSlider(
min: 1,
max: 100,
divisions: 100,
values: values,
labels: labels,
onChanged: (value) {
print('START: ${value.start}, END: ${value.end}');
values = value;
labels = RangeLabels('${values.start.toInt().toString()}\$', '${values.end.toInt().toString()}\$');
setState(() {});
},
//Data from API
)
]);
}
}),
],
),
decoration: BoxDecoration(
color: Colors.cyan[400],
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(30),
topRight: const Radius.circular(30),
)),
),
);
},
)
}),
),
),
),

onPressed: () => {
showModalBottomSheet(
context: context,
builder: (_) =>
StatefulBuilder(builder:(modalContext, modalSetState) => Container(
color: Colors.black,
height: 350,
child: Container(
height:200,
// child: column(),
child: Wrap(
//dropdown button
children: <Widget>[
new Text(values.start.toString()),
ListView.builder(
shrinkWrap: true,
itemCount: 3,
itemBuilder: (context, index) {
context=context;
if (index < 2) {
final sort = _sort[index];
return ExpansionTile(
title: ListTile(
title: Text(
sort.category,
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
),
children: <Widget>[ListTile(title: sort.item)],
);
} else {
return ExpansionTile(
title: ListTile(
title: Text(
'By Price',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
)),
children: <Widget>[
new RangeSlider(
min: 1,
max: 100,
divisions: 100,
values: values,
labels: labels,
onChanged: (value) {
print('START: ${value.start}, END: ${value.end}');
setValuesSlider(value);
labels = RangeLabels('${values.start.toInt().toString()}\$', '${values.end.toInt().toString()}\$');
modalSetState(() {});
},
//Data from API
)
]);
}
}),
],
...
Just use StatefulBuilder(builder:(modalContext, modalSetState)

Related

Query not working correctly when searching ListView with TextFormField

I am listing records from Firebase Firestore with ListView.builder. I convert the incoming records to Model and list them.
I made a search option and I'm trying to make a filtering system for it. I want to filter by nameSurname search, city and district value.
I wrote a code like this:
StreamBuilder(
stream: db
.collection("NeedClothesPeople")
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
final searchText = searchController.text.trim().toLowerCase();
final List<NeedClothesPeopleModel> data = snapshot.data!.docs
.map((e) => NeedClothesPeopleModel.fromDocument(e))
.where((e) =>
searchText.isEmpty ||
e.nameSurname!.toLowerCase().contains(searchText) &&
selectedCity.isEmpty ||
e.city == selectedCity && selectedDistrict.isEmpty ||
e.district == selectedDistrict) // filter
.toList();
return Column(
children: [
const SizedBox(height: 10),
SizedBox(
width: MediaQuery.of(context).size.width * 0.95,
child: TextFormField(
controller: searchController,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
suffixIcon: IconButton(
icon: Icon(Icons.settings),
onPressed: () {
filterModalBottomSheet(context);
},
),
contentPadding: const EdgeInsets.only(),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
),
),
onChanged: (value) {
setState(() {});
},
),
),
SizedBox(
width: double.infinity,
height: MediaQuery.of(context).size.height * 0.8,
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: data.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
leading: Icon(Icons.person),
title: Text(data[index].nameSurname.toString()),
subtitle: Text(
"${data[index].city} / ${data[index].district}",
),
trailing: IconButton(
icon: const Icon(Icons.info),
onPressed: () {
Get.to(const NeedClothesPeopleDetailPage(),
arguments: data[index]);
print(data[index].nameSurname);
},
),
),
);
},
),
),
],
);
}
},
),
void filterModalBottomSheet(BuildContext context) {
showModalBottomSheet(
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(50),
topRight: Radius.circular(50),
),
),
context: context,
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SizedBox(
height: MediaQuery.of(context).size.height * 0.5,
child: Padding(
padding: const EdgeInsets.only(left: 8, right: 8),
child: Column(
children: [
SizedBox(
height: MediaQuery.of(context).size.height * 0.04,
),
Row(
children: [
const Expanded(
flex: 1,
child: Text(
"İl:",
style: TextStyle(fontSize: 19),
),
),
Expanded(
flex: 9,
child: DropdownButtonFormField(
hint: const Text("İl seçiniz"),
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.location_city,
color: Color(0xFFCB3126),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
borderSide: const BorderSide(
color: Color(0xFFCB3126),
),
),
),
items: citys
.map(
(e) => DropdownMenuItem<String>(
value: e.value,
child: e.child,
),
)
.toList(),
onChanged: (value) {
setState(() {
selectedCity = value.toString();
});
},
),
),
],
),
const SizedBox(height: 20),
Row(
children: [
const Expanded(
flex: 1,
child: Text(
"İlçe:",
style: TextStyle(fontSize: 19),
),
),
Expanded(
flex: 9,
child: DropdownButtonFormField(
key: getCityKey(),
hint: selectedCity == ""
? const Text("Önce il seçiniz")
: const Text("İlçe seçiniz"),
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.location_city,
color: Color(0xFFCB3126),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
borderSide: const BorderSide(
color: Color(0xFFCB3126),
),
),
),
items: districtsItem(),
onChanged: (value) {
setState(() {
selectedDistrict = value.toString();
});
},
),
),
],
),
const Spacer(),
Padding(
padding: const EdgeInsets.only(left: 12, right: 12),
child: SizedBox(
width: double.infinity,
height: 50,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFFCB3126),
),
child: const Text(
"Filtrele",
style: TextStyle(fontSize: 20),
),
onPressed: () {
setState(() {
filterActive = true;
Navigator.pop(context);
print(filterActive);
});
},
),
),
),
const SizedBox(height: 10),
],
),
),
);
},
);
},
);
}
The problem is this: When I call it by typing in TextFormField, the records in ListView.builder are changing. However, when filtering is done, the records do not change on the screen.
Why could this be? How can I solve the problem? Thanks.

why I got Another exception was thrown: Incorrect use of ParentDataWidget.?

Hello I'm trying to create a widget of smoothPageIndicator for the introduction of my page. The screen contain picture, title and description. but an exception occured Another exception was thrown: Incorrect use of ParentDataWidget.
this is the code :
#override
Widget buildView() {
var size = MediaQuery.of(context).size;
var textTheme = Theme.of(context).textTheme;
return SafeArea(
child: Scaffold(
floatingActionButton: isSelected
? FloatingActionButton(
backgroundColor: Colors.deepPurple,
onPressed: () {},
child: const Icon(Icons.arrow_forward),
)
: null,
extendBodyBehindAppBar: true,
appBar: AppBar(
backgroundColor: Colors.transparent,
centerTitle: true,
elevation: 0),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(models[currentIndex].imgAssetAddress),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(
Colors.black.withOpacity(0.4), BlendMode.darken),
),
),
child: ClipRRect(
child: Expanded(
flex: 1,
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(
height: 500,
child: PageView.builder(
onPageChanged: (index) {
setState(() {
currentIndex = index;
});
},
controller: _controller,
itemCount: models.length,
itemBuilder: (BuildContext context, int index) {
currentIndex = index;
return GestureDetector(
onTap: () {
setState(() {
if (isSelected == false) {
isSelected = true;
} else {
isSelected = false;
}
});
},
child: Padding(
padding: const EdgeInsets.only(
top: 20, left: 30, right: 30, bottom: 15),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: Colors.white,
border: isSelected
? Border.all(
width: 4,
color: Colors.deepPurple)
: null),
child: Column(
children: [
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(models[index]
.imgAssetAddress),
fit: BoxFit.cover),
borderRadius:
BorderRadius.circular(15),
),
margin: const EdgeInsets.all(10),
height:
MediaQuery.of(context).size.height /
2.4,
),
Expanded(
child: Text(
models[index].city,
style: const TextStyle(
fontSize: 25,
fontWeight: FontWeight.w600),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Expanded(
child: Text(
models[index].description,
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14,
color: Colors.grey[600],
),
)),
),
],
),
),
),
);
}),
),
SmoothPageIndicator(
controller: _controller,
count: models.length,
),
currentIndex == 3
/// GET STARTED BTN
? TextButton(
onPressed: (() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BleScanWindow()),
);
}),
child: const Text("Get Started",
style: TextStyle(color: Colors.blue)),
)
/// SKIP BTN
: SkipBtn(
size: size,
textTheme: textTheme,
onTap: () {
setState(() {
_controller.animateToPage(3,
duration:
const Duration(milliseconds: 1000),
curve: Curves.fastOutSlowIn);
});
})
],
),
My question is how to edit this code to get a clean code and a performant response ?
Thanks in advance for your help
As mentioned, Expanded and Flexible widgets can only be used in Rows and Columns. I noticed that further down you are also using an Expanded inside a Padding widget:
Padding(
padding: const EdgeInsets.all(8.0),
child: Expanded( //// <--- problem
child: Text(
models[index].description,
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14,
color: Colors.grey[600],
),
)),
),
In your source code:
child: ClipRRect(
child: Expanded( //// <--- problem
flex: 1,
child: BackdropFilter(
Here you are using an Expanded widget inside a ClipRRect, which is causing the issue you are seeing.
Expanded is a ParentDataWidget that only works inside a Flex (like Row or Column widget), it cannot be used as a child to a ClipRRect widget like you did.

A RenderViewport expected a child of type RenderSliver but received a child of type RenderPositionedBox

encountered this error after changing some labels, I don't even remember changing the widgets:
I know that this is a sliver and box issue but I tried changing and removing widgets to fix this problem to no avail
return Scaffold(
backgroundColor: Colors.grey[200],
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: () {
//PATIENT.
if (currTab == 0) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const AddPatient(),
),
);
} else {
//SHIPMENT.
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const AddShipment(),
),
);
}
},
heroTag: null,
child: Icon(currTab == 0
? Icons.person_add
: Icons.add_shopping_cart_rounded),
),
const SizedBox(
height: 10,
),
currTab == 0 ? _getFAB() : const SizedBox(),
// FloatingActionButton(
// onPressed: () {},
// heroTag: null,
// child: const Icon(Icons.sort_rounded),
// ),
],
),
resizeToAvoidBottomInset: true,
body: DefaultTabController(
length: 2,
child: NestedScrollView(
body: TabBarView(
controller: _tabController,
physics: const NeverScrollableScrollPhysics(),
children: [
StreamBuilder<List<Patient>>(
stream: readPatients(orderTypePatients),
builder: (context, snapshot) {
if (snapshot.hasData) {
countPatients = snapshot.data!.length;
} else {
countPatients = 0;
}
return CustomScrollView(
slivers: [
if (snapshot.hasData)
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
if (snapshot.hasData) {
final patient = snapshot.data;
return makeCardPatient(patient![index]);
} else if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(
color: Colors.green),
);
} else if (snapshot.hasError) {
return const SliverToBoxAdapter(
child: Center(child: Text('has err')));
} else {
return const Center(
child: CircularProgressIndicator(
color: Colors.green),
);
}
},
childCount: snapshot.data?.length,
),
)
else if (snapshot.hasError)
Center(
child: Text(
snapshot.error.toString(),
style: const TextStyle(fontWeight: FontWeight.bold),
),
)
else
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(10.0),
child: Center(
child: CircularProgressIndicator(
color: Colors.green,
),
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
'Total:\n$totalSumPatients',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 21,
),
),
],
),
),
),
],
);
},
),
StreamBuilder<List<Shipment>>(
stream: readShipments(orderTypeShipments),
builder: (context, snapshot) {
if (snapshot.hasData) {
countShipments = snapshot.data!.length;
} else {
countShipments = 0;
}
return CustomScrollView(
slivers: [
if (snapshot.hasData)
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
if (snapshot.hasData) {
final shipment = snapshot.data;
return makeCardShipment(shipment![index]);
} else if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(
color: Colors.green),
);
} else if (snapshot.hasError) {
return const SliverToBoxAdapter(
child: Center(child: Text('has err')));
} else {
return const Center(
child: CircularProgressIndicator(
color: Colors.green),
);
}
},
childCount: snapshot.data?.length,
),
)
else if (snapshot.hasError)
SliverToBoxAdapter(
child: Center(
child: Text(
snapshot.error.toString(),
style: const TextStyle(fontWeight: FontWeight.bold),
),
))
else
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(10.0),
child: Center(
child: CircularProgressIndicator(
color: Colors.green,
),
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Center(
child: Text(
'Total:\n$totalSumShipment',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.w900,
fontSize: 21,
),
),
),
),
),
],
);
},
),
],
),
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return [
SliverAppBar(
stretch: true,
bottom: TabBar(
controller: _tabController,
indicatorSize: TabBarIndicatorSize.tab,
indicatorColor: Colors.green,
indicatorWeight: 5,
labelColor: Colors.green,
labelStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
unselectedLabelColor: Colors.grey,
overlayColor:
MaterialStateProperty.all<Color>(Colors.grey[300]!),
onTap: (value) {
totalSumShipment = 0;
totalSumPatients = 0;
searchController.clear();
FocusManager.instance.primaryFocus?.unfocus();
currTab = value;
setState(() {});
},
tabs: [
Tab(
icon: Stack(
children: [
Icon(
Icons.supervised_user_circle_rounded,
color: currTab == 0 ? Colors.green : Colors.grey,
size: 36,
),
countPatients == 0
? const SizedBox(
height: 1,
)
: Positioned(
right: 0,
child: Container(
padding: const EdgeInsets.all(1),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(7),
),
constraints: const BoxConstraints(
minWidth: 15,
minHeight: 15,
maxHeight: 15,
maxWidth: 15,
),
child: Text(
countPatients.toInt().toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 10,
),
textAlign: TextAlign.center,
),
),
),
],
),
text: 'Patients',
),
Tab(
icon: Stack(
children: [
Icon(
Icons.shopping_bag_rounded,
color: currTab == 1 ? Colors.green : Colors.grey,
size: 36,
),
countShipments == 0
? const SizedBox(
height: 1,
)
: Positioned(
right: 0,
child: Container(
padding: const EdgeInsets.all(1),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(7),
),
constraints: const BoxConstraints(
minWidth: 15,
minHeight: 15,
maxHeight: 15,
maxWidth: 15,
),
child: Text(
countShipments.toInt().toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 10,
),
textAlign: TextAlign.center,
),
),
),
],
),
text: 'Orders',
),
],
),
pinned: true,
snap: false,
floating: true,
elevation: 10,
expandedHeight: 300.0,
stretchTriggerOffset: 150.0,
backgroundColor: Colors.grey.shade200,
flexibleSpace: FlexibleSpaceBar(
stretchModes: const [
StretchMode.zoomBackground,
StretchMode.fadeTitle,
StretchMode.blurBackground,
],
titlePadding: const EdgeInsetsDirectional.all(0),
background: SafeArea(
child: Stack(
alignment: AlignmentDirectional.topCenter,
fit: StackFit.loose,
children: [
Positioned(
top: 5,
right: 5,
child: IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SettingsPage(),
),
);
},
icon: const Icon(Icons.settings_rounded)),
),
Positioned(
top: 10,
right: 1,
left: 1,
child: Padding(
padding: const EdgeInsets.all(50.0),
child: GestureDetector(
onTap: () {
log(countShipments.toString());
setState(() {});
},
child: Image.asset(
'assets/images/my_Logo.png',
fit: BoxFit.fitWidth,
),
),
),
),
Positioned(
top: 120,
left: 10,
right: 10,
child: Padding(
padding: const EdgeInsets.all(30.0),
child: searchField(),
),
),
],
),
),
centerTitle: true,
collapseMode: CollapseMode.pin,
),
)
];
},
),
),
);
↑ is the scaffold
Card makeCardPatient(Patient patient) {
totalSumPatients = totalSumPatients + patient.balance;
return Card(
elevation: 8.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0),
),
margin: const EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 6.0,
),
child: Container(
decoration: BoxDecoration(
color: const Color.fromARGB(228, 64, 96, 72),
borderRadius: BorderRadius.circular(25),
),
child: makeListTilePatient(patient),
),
);
}
↑ is the card wiget that is called in the streambuilder to create the Card widget
ListTile makeListTilePatient(Patient patient) {
return ListTile(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 20.0,
vertical: 10.0,
),
leading: Container(
padding: const EdgeInsets.only(right: 12.0),
decoration: const BoxDecoration(
border: Border(
right: BorderSide(
width: 1.0,
color: Colors.white24,
),
),
),
child: CircleAvatar(
radius: 25,
backgroundColor: patient.balance == 0 ? Colors.blue : Colors.red,
child: Text(
patient.balance.toStringAsFixed(2).toUpperCase(),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
),
),
title: Text(
patient.name,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
flex: 1,
child: Text(
DateFormat('yyyy/MM/dd').format(patient.lastvisit) == '1986/09/25'
? ' '
: timeAgo(patient.lastvisit),
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.only(left: 10.0),
child: Text(
DateFormat('yyyy/MM/dd').format(patient.appointment) ==
'1986/09/25'
? ' '
: timeFromNow(patient.appointment),
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
)
],
),
trailing: const Icon(
Icons.keyboard_arrow_right,
color: Colors.white,
size: 30.0,
),
onTap: () {
totalSumPatients = 0;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Details(
patient: patient,
),
),
);
setState(() {});
},
);
}
↑ is the Tile widget to detail whats in the card.
I know that there is something that I'm not seeing but tried searching and editing for a long while and I didnt find what I'm missing.
I'm new to SO can you please help me?
I tried wrapping some widgets with Slivertoboxadapter but didnt work.
extra functions used ,I dont think they are related to the problem but here they are:
Stream<List<Shipment>> readShipments(String orderTypeShipments) {
return FirebaseFirestore.instance
.collection('shipments')
.orderBy(
orderTypeShipments,
descending: sortOrder,
)
.snapshots()
.map((snapshot) => snapshot.docs
.map((doc) => Shipment.fromJson(doc.data()))
.where(
(element) =>
element.userId.toUpperCase() ==
Helper.currUserID.toUpperCase() &&
element.type.toUpperCase().contains(
searchController.text.toUpperCase(),
),
)
.toList());
}
Future<int> getPatientCount() async {
var x = FirebaseFirestore.instance
.collection('patients')
.orderBy(
orderTypePatients.toUpperCase(),
descending: sortOrder,
)
.snapshots()
.map((snapshot) => snapshot.docs
.map((doc) => Patient.fromJson(doc.data()))
.where((element) =>
element.user == Helper.currUserID &&
(element.name
.toUpperCase()
.contains(searchController.text.toUpperCase())))
.toList());
setState(() {});
return x.length;
}
As suggested by #Yeasin Sheikh I overlooked that line, silly me.
thanks yeasin.
I just had to wrap the Center widget with a SliverToBoxAdapter in the snapshot.error:
SliverToBoxAdapter(child:Center(...

How to fix this UI problem in my Flutter app?

Hello guys this is my first flutter app. I have to do a screen like an image below:
This is what I've got:
My problem is I couldn't display the add button over the circular container and if I change the text in a chip the other chips text changes too.
Like this:
This is my code:
Widget ExpertiseRow() {
void _addNewExpertiseRow() {
setState(() {
count = count + 1;
});
}
return new Container(
width: 170.0,
padding: new EdgeInsets.all(5.0),
child: new Column(children: <Widget>[
Chip(
onDeleted: () {
setState(() {
count = count - 1;
chips.removeAt(count + 1);
print(chips.toList());
});
},
deleteIcon: Icon(
Icons.close,
color: Colors.white,
size: 20,
),
backgroundColor: Colors.black,
avatar: Container(
width: 450,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20))),
child: IconButton(
//iconSize: 40,
icon: Icon(
Icons.add,
color: Colors.black,
size: 30,
),
onPressed: _addNewExpertiseRow)),
label: EditableText(
controller: controller,
onSubmitted: (text) {
chips.add(text);
print(chips.toList());
setState(() {
chips = chips;
});
},
focusNode: FocusNode(),
backgroundCursorColor: Colors.white,
cursorColor: Colors.white,
style: TextStyle(color: Colors.white),
),
),
new Container(
//padding: new EdgeInsets.all(10.0),
child: InkWell(
onTap: _addNewContactRow,
child: Image.asset(
'assets/images/add.png',
height: 50,
width: 50,
fit: BoxFit.cover,
)), /*IconButton(
alignment: Alignment.topCenter,
icon: Icon(
Icons.add,
color: Colors.black,
size: 30,
),
onPressed: _addNewContactRow))*/
)
]));
}
#override
Widget build(BuildContext context) {
var height =
MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top;
var space = height > 650 ? kSpaceM : kSpaceS;
List<Widget> _expertises =
new List.generate(count, (int i) => ExpertiseRow());
return new Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
appBar: new AppBar(
title: new Center(
child: new Text(
"Compte Entrepreneur",
style: TextStyle(
fontSize: 25.0,
color: Colors.black,
),
)),
elevation: 0.0,
backgroundColor: Colors.white,
),
body: Form(
key: _formKey,
child: new LayoutBuilder(builder: (context, constraint) {
return new Center(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 40,
),
new Text(
"Nom et prénom",
style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
FadeSlideTransition(
animation: _formElementAnimation,
additionalOffset: space,
child: CustomInputField(
label: 'Votre nom',
prefixIcon: Icons.person,
obscureText: false,
textController: _fullnameController,
validator: ValidatorService.fullNameValidate,
onChanged: (text) {
name = text;
print(name);
},
)),
new Container(
padding: new EdgeInsets.all(30.0),
),
new Text(
"Position",
style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
FadeSlideTransition(
animation: _formElementAnimation,
additionalOffset: space,
child: CustomInputField(
label: 'Position',
prefixIcon: Icons.work,
obscureText: false,
textController: _positionController,
validator: ValidatorService.positionValidate,
onChanged: (text) {
position = text;
print(position);
},
)),
new Container(
padding: new EdgeInsets.all(30.0),
),
new Text(
"Expertises",
style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
//the chips input
FadeSlideTransition(
animation: _formElementAnimation,
additionalOffset: space,
child: new Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.all(Radius.elliptical(20, 20)),
border: Border.all(
width: 3,
),
),
height: 130.0,
width: 370.0,
child: new ListView(
children: _expertises,
scrollDirection: Axis.horizontal,
),
)),
new Container(
padding: new EdgeInsets.all(55.0),
),
new Container(
width: 350,
//color: Colors.blue,
//padding: new EdgeInsets.all(10.0),
child: Row(children: <Widget>[
Container(
width: 270,
),
new Container(
width: 60,
color: Colors.black,
child: IconButton(
icon: Icon(
Icons.arrow_forward,
color: Colors.white,
size: 30,
),
onPressed: () {
if (_formKey.currentState.validate()) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => InterestsPage(),
),
);
}
}))
])),
],
),
);
})));
}
}
I also want to add the chips text to a list.
Looking forward to your help. Thanks in advance

Duplicate GlobalKey detected in Widget Tree or Multiple Widgets used the same GlobalKey

I've tried to create form to input something from textfield to database using rest service, it worked just fine from the first try, but it got error the next time I tried, the error said there was something wrong with the GlobalkKey, so it's maybe around here.
class _DeliveryRecieverState extends State<DeliveryReciever> {
List datas;
File imagePath;
bool validasi = false;
String namaPenerima;
final _keyFormReceiver = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
datas = this.datas;
print(datas);
return DefaultTabController(
length: 1,
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
bottom: TabBar(
tabs: <Widget>[
Tab(
icon: Icon(Icons.local_shipping),
text: "Bukti Delivery",
),
],
),
elevation: 0.1,
// backgroundColor: Colors.cyan[800],
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF17ead9), Color(0xFF6078ea)]),
),
),
title: Text(
"Delivery",
style: TextStyle(
fontFamily: "Popins-Bold",
fontSize: ScreenUtil.getInstance().setSp(46),
letterSpacing: .6,
fontWeight: FontWeight.bold,
),
),
actions: <Widget>[
],
),
body: TabBarView(
children: <Widget>[
SingleChildScrollView(
child: Padding(
padding: EdgeInsets.only(
left: 15.0, right: 15.0, top: 15.0, bottom: 15.0),
child: Column(
children: <Widget>[
Container(
width: double.infinity,
height: ScreenUtil.getInstance().setHeight(470),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8.0),
boxShadow: [
BoxShadow(
color: Colors.black12,
offset: Offset(0.0, 15.0),
blurRadius: 15.0),
BoxShadow(
color: Colors.black12,
offset: Offset(0.0, -10.0),
blurRadius: 10.0)
]),
child: Padding(
padding: EdgeInsets.only(
left: 16.0, right: 16.0, top: 16.0),
child: Form(
key: _keyFormReceiver,
autovalidate: validasi,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Nama Penerima",
style: TextStyle(
fontSize:
ScreenUtil.getInstance().setSp(30),
fontFamily: "Poppins-Bold",
letterSpacing: .6),
),
SizedBox(
height:
ScreenUtil.getInstance().setHeight(30),
),
TextFormField(
validator: validasiReceivername,
onSaved: (String nama) {
namaPenerima = nama;
},
decoration: InputDecoration(
hintText: "Nama Penerima",
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 12.0)),
),
SizedBox(
height:
ScreenUtil.getInstance().setHeight(50),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: RaisedButton(
elevation: 7.0,
color: Colors.green,
padding: EdgeInsets.all(20.0),
child: Text("LANJUT"),
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(10)),
onPressed: () {
parseData();
},
),
),
],
),
],
),
)),
),
],
),
),
),
],
),
bottomNavigationBar: Container(
height: 55.0,
child: BottomAppBar(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF17ead9), Color(0xFF6078ea)]),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
icon: Icon(Icons.home, color: Colors.white),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => halamanUtama()),
);
},
),
IconButton(
icon: Icon(Icons.nature_people, color: Colors.white),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UpcomingDelivery()),
);
},
),
IconButton(
icon: Icon(Icons.local_shipping, color: Colors.white),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ListDelivery()),
);
},
),
],
),
),
),
),
));
}
String validasiReceivername(String value) {
if (value.length == 0) {
//Toast.show("Password more than 4 ", context,duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
return "Nama penerima tidak boleh kosong.";
} else {
return null;
}
}
void parseData() async {
if (_keyFormReceiver.currentState.validate()) {
_keyFormReceiver.currentState.save();
_keyFormReceiver.currentState.reset();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CustomerSignatureProof(
created_name: widget.created_name,
wmsorders_id: widget.wmsorders_id,
imagePath: widget.imagePath,
imageName: widget.imageName,
receiverName: namaPenerima,
upcoming_id: widget.upcoming_id,
upcoming_sku: widget.upcoming_sku,
upcoming_sak: widget.upcoming_sak,
upcoming_qty: widget.upcoming_qty,
upcoming_shipstatid: widget.upcoming_shipstatid,
upcoming_picname: widget.upcoming_picname,
upcoming_pictelp: widget.upcoming_pictelp,
upcoming_ordermultipleid: widget.upcoming_ordermultipleid,
upcoming_orderdetid: widget.upcoming_orderdetid,
upcoming_coordinatorid: widget.upcoming_coordinatorid,
upcoming_shipmentid: widget.upcoming_shipmentid)));
}
}
}
Here is the error in terminal,
Have anybody face the same probles as me, please give your guidance..