'child == _child': is not true , Duplicate GlobalKey detected in widget tree - android

I am getting this error when I render a child component in flutter.
Failed assertion: line 6075 pos 12: 'child == _child': is not true.
Duplicate GlobalKey detected in widget tree.
A RenderShrinkWrappingViewport expected a child of type RenderSliver but received a child of type RenderFlex.
my code is here.........
// #dart=2.9
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_project/constants.dart';
import 'package:flutter_project/provider/store_provider.dart';
import 'package:flutter_project/services/store_services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:paginate_firestore/bloc/pagination_listeners.dart';
import 'package:paginate_firestore/paginate_firestore.dart';
import 'package:provider/provider.dart';
class NearByStore extends StatefulWidget {
#override
_NearByStoreState createState() => _NearByStoreState();
}
class _NearByStoreState extends State<NearByStore> {
StoreServices _storeServices = StoreServices();
PaginateRefreshedChangeListener refreshedChangeListener = PaginateRefreshedChangeListener();
#override
Widget build(BuildContext context) {
final _storeData = Provider.of<StoreProvider>(context);
_storeData.getUserLocationData(context);
String getDistance(location) {
var distance = Geolocator.distanceBetween(
_storeData.userLatitude, _storeData.userLongitude, location.latitude,
location.longitude);
var distanceInKm = distance / 1000;
return distanceInKm.toStringAsFixed(2);
}
return Container(
child: StreamBuilder<QuerySnapshot>(
stream: _storeServices.getTopPickedStore(), // will change it soon
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot>snapShot) {
if (!snapShot.hasData) return
CircularProgressIndicator();
List shopDistance = [];
for (int i = 0; i <= snapShot.data.docs.length - 1; i++) {
var distance = Geolocator.distanceBetween(
_storeData.userLatitude, _storeData.userLongitude,
snapShot.data.docs[i]['location'].latitude,
snapShot.data.docs[i]['location'].longitude);
var distanceInKm = distance / 1000;
shopDistance.add(distanceInKm);
}
shopDistance
.sort(); // this will sort with nearest distance. if nearest distance is more than 10, that means no shop near by;
if (shopDistance[0] > 10) {
return Container(
child: Stack(
children: [
Center(
child: Text('***That all folks***',
style: TextStyle(color: Colors.grey),),
),
Image.asset(
'images/city.png', color: Colors.black12),
Positioned(
right: 10.0,
top: 80,
child: Container(
width: 100,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Made by : ', style: TextStyle(
color: Colors.black54
),),
Text('VOID TECHNOLOGY', style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Anton',
letterSpacing: 2,
color: Colors.grey
),)
],
),
),
)
],
),
);
}
return Padding(
padding: EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RefreshIndicator(
child: PaginateFirestore(
bottomLoader: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Theme
.of(context)
.primaryColor),
),
header: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(
left: 8, right: 8, top: 20
),
child: Text('All Nearby Stores',
style: TextStyle(fontWeight: FontWeight.w900,
fontSize: 18
),),
),
Padding(
padding: const EdgeInsets.only(
left: 8, right: 8, bottom: 10
),
child: Text('Findout quality products near you',
style: TextStyle(
fontSize: 12, color: Colors.grey
),),
),
],
),
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilderType: PaginateBuilderType.listView,
itemBuilder: (index, context, document) =>
Padding(
padding: const EdgeInsets.all(4),
child: Container(
width: MediaQuery
.of(context)
.size
.width,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 100,
height: 110,
child: Card(
child: ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.network(document['imageUrl'],
fit: BoxFit.cover,
),
),
),
),
SizedBox(width: 10,),
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
child: Text(
document['shopName'], style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
SizedBox(
height: 3,
),
Text(document['dialog'],
style: kStoreCardStyle,),
SizedBox(
height: 3,
),
Container(
width: MediaQuery
.of(context)
.size
.width - 250,
child: Text(document['address'],
overflow: TextOverflow.ellipsis,
style: kStoreCardStyle,
),
),
SizedBox(
height: 3,
),
Text(
'${getDistance(document['location'])}Km',
overflow: TextOverflow.ellipsis,
),
SizedBox(
height: 3,
),
Row(
children: [
Icon(
Icons.star,
size: 12,
color: Colors.grey,
),
SizedBox(
width: 4,
),
Text('3.2', style: kStoreCardStyle,)
],
)
],
)
],
),
),
),
query: FirebaseFirestore.instance.collection('vendors')
.where('accVerified', isEqualTo: true)
.where('isTopPicked', isEqualTo: true).orderBy(
'shopName'),
listeners: [
refreshedChangeListener,
],
footer: Padding(
padding: const EdgeInsets.only(top: 30),
child: Container(
child: Stack(
children: [
Center(
child: Text('***That all folks***',
style: TextStyle(color: Colors.grey),),
),
Image.asset(
'images/city.png', color: Colors.black12),
Positioned(
right: 10.0,
top: 80,
child: Container(
width: 100,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Made by : ', style: TextStyle(
color: Colors.black54
),),
Text('VOID TECHNOLOGY', style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Anton',
letterSpacing: 2,
color: Colors.grey
),)
],
),
),
)
],
),
),
),
),
onRefresh: () async {
refreshedChangeListener.refreshed = true;
},
)
],
),
);
},
),
);
}
}
======== Exception caught by widgets library =======================================================
The following assertion was thrown building RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#a5a30](state: RawGestureDetectorState#b8caf(gestures: <none>, behavior: opaque)):
'package:flutter/src/widgets/framework.dart': Failed assertion: line 6075 pos 12: 'child == _child': is not true.
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md
The relevant error-causing widget was:
PaginateFirestore file:///E:/Flutter%20Main/flutter_project/lib/widgets/near_by_store.dart:99:26
When the exception was thrown, this was the stack:
#2 SingleChildRenderObjectElement.forgetChild (package:flutter/src/widgets/framework.dart:6075:12)
#3 Element._retakeInactiveElement (package:flutter/src/widgets/framework.dart:3563:14)
... Normal element mounting (10 frames)
#13 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3611:14)
#14 Element.updateChild (package:flutter/src/widgets/framework.dart:3360:20)
======== Exception caught by widgets library =======================================================
The following assertion was thrown while finalizing the widget tree:
Duplicate GlobalKey detected in widget tree.
The following GlobalKey was specified multiple times in the widget tree. This will lead to parts of the widget tree being truncated unexpectedly, because the second time a key is seen, the previous instance is moved to the new location. The key was:
- [GlobalKey#4acc7]
This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.
The specific parent that did not update after having one or more children forcibly removed due to GlobalKey reparenting is:
- Semantics(container: false, properties: SemanticsProperties, label: null, value: null, hint: null, hintOverrides: null, renderObject: RenderSemanticsAnnotations#faf5c NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE DETACHED)
A GlobalKey can only be specified on one widget at a time in the widget tree.
When the exception was thrown, this was the stack:
#0 BuildOwner.finalizeTree.<anonymous closure> (package:flutter/src/widgets/framework.dart:2900:15)
#1 BuildOwner.finalizeTree (package:flutter/src/widgets/framework.dart:2925:8)
#2 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:877:19)
#3 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
#4 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1082:9)
...
====================================================================================================

The header and footer properties are expected to be Slivers. so in order to use non-sliver widgets, you can wrap them with SliverToBoxAdapter which is "a sliver that contains a single box widget."
Try like this.
Update the Header code to:
header: SliverToBoxAdapter(
child: Column(
...
),
),
And update the footer code to:
footer: SliverToBoxAdapter(
child: Padding(
...
)
),

Related

Flutter Stack Widget inside ListView widget?

I am using the Stack widget in my app and it is working great but now I have a problem with wrapping this Stack widget inside ListView Widget.
I am getting error
RenderBox was not laid out: RenderPointerListener#20d10 relayoutBoundary=up7 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1979 pos 12: 'hasSize'
My Stack Widget is
Widget? stackW() {
return Stack(
alignment: Alignment.center,
children: <Widget>[
Positioned(
top: 70,
width: MediaQuery.of(context).size.width * .9,
height: 150,
child: Center(
child: Container(
width: MediaQuery.of(context).size.width * .9,
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(15)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Product Designer",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
const SizedBox(
height: 10,
),
],
),
),
),
),
Positioned(
top: 30,
left: MediaQuery.of(context).size.width / 2.5,
width: 80,
height: 80,
child: CircleAvatar(
backgroundColor: Colors.white,
child: CircleAvatar(
backgroundColor: Colors.green[100],
radius: 35,
child: const FaIcon(
FontAwesomeIcons.apple,
size: 30,
color: Colors.black,
),
),
),
),
],
);
}
When I am passing stackWidget directly in body then it is working fine but after wrapping inside ListView, it is creating problem.
so Please guide me to achieve my listview data with Stack Widget.
body: stackW()!, //working
body: ListView(
scrollDirection: Axis.vertical,
children: [
stackW()!,
],
),
``` //not working
Both widgets are getting infinite height, you can wrap stackW() with SizedBox widget.
body: LayoutBuilder(
builder: (context, constraints) => ListView(
scrollDirection: Axis.vertical,
children: [
SizedBox(
height: constraints.maxHeight,
width: constraints.maxWidth,
child: stackW()!,
)
],
),
),

I am trying to wrap my Column widget in a SingleChildScrollView but not able to

I am trying to wrap my column widget in a single child scroll view since I am getting overflow. But when I am trying to wrap it, I am receiving errors such as
RenderFlex children have non-zero flex but incoming height constraints are unbounded.
RenderBox was not laid out: RenderFlex#dc736 relayoutBoundary=up12 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'
What can I do to prevent overflow of pixels in my app ? Here is my code:
return Scaffold(
appBar: AppBar(
title: Text('Edit your pet`s details'),
backgroundColor: Color.fromRGBO(101, 69, 112, 1.0),
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget> [
Row(
children: <Widget>[
Expanded(
child: TextFieldWidget(
controller: _petNameController,
helperText: "Pet's Name",
)),
],
),
Padding(
padding: const EdgeInsets.only(left: 50.0, right: 50.0),
child: Divider(
color: Colors.grey,
thickness: 0.5,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 60.0,),
Text(
"$_petName is a $_petGender. Update gender",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w400,
),
)
],
),
Expanded(
child: GridView.count(
crossAxisCount: 2,
primary: false,
scrollDirection: Axis.vertical,
children: List.generate(petGenders.length, (index) {
return GestureDetector(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0)),
color:
selectedIndex == index ? primaryColor : null,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
petGenders[petKeys[index]],
SizedBox(
height: 15.0,
),
Text(
petKeys[index],
style: TextStyle(
color: selectedIndex == index
? Colors.white
: null,
fontSize: 18.0,
fontWeight: FontWeight.w600),
),
],
),
),
),
onTap: () {
setState(() {
widget.pet.gender = petKeys[index];
selectedIndex = index;
});
});
}),
),
),
The error comes from the fact that your Column contains an Extended widget, which forces to use the maximum vertical space.
The SingleScrollChildView has no limit to vertical space it can use.
The result is that you have a widget that try to take an infinite vertical space.
How can you fix that ?
Either, remove the Extended widget, or the SingleScrollChildView widget.
Or, you can also wrap your Extended widget with another widget with a defined size or constraints like a Container with the properties height and width.

How to delete blank spaces or null Container in SliverGrid.count?

I'm trying to delete the Null Container in SliverGrid.count after validated the map entries . I wish the issue arrive you . thanks in advance for you solution .
class myGridItem extends StatefulWidget {
final Item item;
final EdgeInsets? margin;
const myGridItem({
Key? key,
required this.item,
this.margin,
}) : super(key: key);
#override
_myGridItemState createState() => _myGridItemState();
}
class _myGridItemState extends State<myGridItem> {
#override
Widget build(BuildContext context) {
return Container(
margin: widget.margin == null ? EdgeInsets.zero : widget.margin,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(7),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
offset: Offset.zero,
blurRadius: 15.0,
)
],
),
child: Column(
children: [
Expanded(
child: Stack(
alignment: Alignment.center,
children: [
Container(
margin: EdgeInsets.only(top: 37),
height: 180,
decoration: BoxDecoration(
image: DecorationImage(
alignment: Alignment.bottomCenter,
image: AssetImage(widget.item.imagePath),
),
),
),
// --------------------------- create favourit widget
Positioned(
top: 16,
right: 16,
child: Container(
width: 40,
height: 40,
alignment: Alignment.center,
decoration: BoxDecoration(
color: primaryColor,
shape: BoxShape.circle,
),
child: Text(
'999%',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
),
),
// ------------------------- discont missing
],
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.item.name,
style: TextStyle(
color: Colors.black,
fontSize: 13,
height: 1.5,
),
),
SizedBox(
height: 10,
),
Wrap(
spacing: 3,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'${Item.format(widget.item.price)}',
style: TextStyle(
fontSize: 18,
color: primaryColor,
height: 1.5,
),
),
],
)
],
),
],
),
)
],
),
);
}
}
Here the creation of SliverGrid.count to display the items I tried to use SliverChildBuilderDelegate but the same issue after some Editing on it to reach the same level of SliverGrid.count .
class myCartItemDisplay extends StatefulWidget {
#override
_myCartItemDisplayState createState() => _myCartItemDisplayState();
}
class _myCartItemDisplayState extends State<myCartItemDisplay> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: myAppBar(
title: 'Cart',
myBarColor: Colors.white,
mybackWidget: HomeScreen(),
),
bottomNavigationBar: AppBottomNavigation(),
backgroundColor: Colors.white,
body: SafeArea(
child: CustomScrollView(
slivers: [
Container(
child: SliverGrid.count(
crossAxisCount: 2,
childAspectRatio: 0.65,
mainAxisSpacing: 16,
crossAxisSpacing: 16,
children: Fake.furniture.asMap().entries.map((f) {
return Container(
child: f.value.addToCart == 1
? myGridItem(
item: f.value,
margin: EdgeInsets.only(
left: f.key.isEven ? 16 : 0,
right: f.key.isOdd ? 16 : 0,
))
: null,
);
}).toList(),
),
),
],
),
),
);
}
}
You can add a filter before your map:
children: Fake.furniture.asMap().entries
.where((f) => f.value.addToCart == 1)
.map((f) {
return Container(
child: myGridItem(
item: f.value,
margin: EdgeInsets.only(
left: f.key.isEven ? 16 : 0,
right: f.key.isOdd ? 16 : 0,
),
),
);
}).toList(),
This way you won't end up with any null entries in the first place.
I fixed it by add a new List it has my target entries
List<Item> _names = Fake.furniture.where((i) => i.addToCart == 1).toList();
And then :
_names.asMap().entries.map((f)
But if you have another solution with flutter give us it , thanks

- How to fix it : Incorrect use of ParentDataWidget?

I am getting Error Incorrect use of ParentDataWidget.
And the lists not show the item in first time.
The ParentDataWidget Expanded(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type ParentData.
Usually, this means that the Expanded widget has the wrong ancestor RenderObjectWidget. Typically, Expanded widgets are placed directly inside Flex widgets.
The offending Expanded is currently placed inside a ConstrainedBox widget.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: () {},
)
],
backgroundColor: Colors.green,
),
drawer: Drawer(
child: AppDrawer(),
),
body: SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(),
child: Column(
children: <Widget>[
Container(
height: 200,
width: double.infinity,
child: HomeSlider(),
),
Padding(
padding: EdgeInsets.only(top: 14.0, left: 8.0, right: 8.0),
child: Text(
AppLocalizations.of(context)
.translate('leatest_producrs'),
style: TextStyle(
color: Theme.of(context).accentColor,
fontSize: 18,
fontWeight: FontWeight.w700)),
),
Container(
margin: EdgeInsets.symmetric(vertical: 8.0),
height: 200.0,
child: Expanded(
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: cards.length,
itemBuilder: (BuildContext context, int index) => Card(
child: InkWell(
child: Column(
children: [
Flexible(
child: Container(
height: double.infinity,
width: 120,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
cards[index].productImg,
),
fit: BoxFit.fitHeight,
)),
),
),
Container(
width: 150,
padding: EdgeInsets.all(10),
child: Text(cards[index].productName,
style: new TextStyle(fontSize: 12),
softWrap: true),
),
],
),
onTap: () {
Fluttertoast.showToast(
msg: cards[index].productName,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.white70,
textColor: Colors.black,
fontSize: 16.0);
},
),
),
),
),
),
Container(
child: Padding(
padding: EdgeInsets.only(top: 6.0, left: 8.0, right: 8.0),
child: Image(
fit: BoxFit.cover,
image: AssetImage('assets/images/banner-1.jpg'),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0),
child: Text('Featured Products',
style: TextStyle(
color: Theme.of(context).accentColor,
fontSize: 18,
fontWeight: FontWeight.w700)),
),
Padding(
padding: const EdgeInsets.only(
right: 8.0, top: 8.0, left: 8.0),
child: RaisedButton(
color: Theme.of(context).primaryColor,
child: Text('View All',
style: TextStyle(color: Colors.white)),
onPressed: () {
Navigator.pushNamed(context, '/categorise');
}),
)
],
),
Container(
child: GridView.count(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
crossAxisCount: 2,
padding:
EdgeInsets.only(top: 8, left: 6, right: 6, bottom: 12),
children: List.generate(cards.length, (index) {
return Container(
child: Card(
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () {
print('Card tapped.');
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Flexible(
child: Container(
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
cards[index].productImg,
),
fit: BoxFit.fitHeight,
)),
),
),
ListTile(
title: Text(
cards[index].productName,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 12),
)),
],
),
),
),
);
}),
),
),
Container(
child: Padding(
padding: EdgeInsets.only(
top: 6.0, left: 8.0, right: 8.0, bottom: 10),
child: Image(
fit: BoxFit.cover,
image: AssetImage('assets/images/banner-2.jpg'),
),
),
)
],
),
),
));
Error Codes are
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.
The ParentDataWidget Expanded(flex: 1) wants to apply ParentData of type FlexParentData to a
RenderObject, which has been set up to accept ParentData of incompatible type ParentData.
Usually, this means that the Expanded widget has the wrong ancestor RenderObjectWidget. Typically,
Expanded widgets are placed directly inside Flex widgets.
The offending Expanded is currently placed inside a ConstrainedBox widget.
The ownership chain for the RenderObject that received the incompatible parent data was:
RepaintBoundary ← NotificationListener<ScrollNotification> ← GlowingOverscrollIndicator ←
Scrollable ← ListView ← Expanded ← ConstrainedBox ← Padding ← Container ← Column ← ⋯
When the exception was thrown, this was the stack:
.
.
.
.
(elided 4 frames from class _RawReceivePortImpl, class _Timer, and dart:async-patch)
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.
The ParentDataWidget Expanded(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type ParentData.
Usually, this means that the Expanded widget has the wrong ancestor RenderObjectWidget. Typically, Expanded widgets are placed directly inside Flex widgets.
The offending Expanded is currently placed inside a ConstrainedBox widget.
The ownership chain for the RenderObject that received the incompatible parent data was:
RepaintBoundary ← NotificationListener<ScrollNotification> ← GlowingOverscrollIndicator ← Scrollable ← ListView ← Expanded ← ConstrainedBox ← Padding ← Container ← Column ← ⋯
When the exception was thrown, this was the stack:
#0 RenderObjectElement._updateParentData.<anonymous closure> (package:flutter/src/widgets/framework.dart:5689:11)
#1 RenderObjectElement._updateParentData (package:flutter/src/widgets/framework.dart:5705:6)
#2 ParentDataElement._applyParentData.applyParentDataToChild (package:flutter/src/widgets/framework.dart:4939:15)
#3 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4600:14)
#4 ParentDataElement._applyParentData.applyParentDataToChild (package:flutter/src/widgets/framework.dart:4942:15)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
You can copy paste run full code below
In your case, you do not need Expanded because you already set Container height to 200
code snippet
Container(
margin: EdgeInsets.symmetric(vertical: 8.0),
height: 200.0,
child: ListView.builder(
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class CardItem {
String productImg;
String productName;
CardItem({this.productImg, this.productName});
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
List<CardItem> cards = [
CardItem(productImg: "https://picsum.photos/250?image=9", productName: "a"),
CardItem(
productImg: "https://picsum.photos/250?image=10", productName: "b"),
CardItem(
productImg: "https://picsum.photos/250?image=11", productName: "c"),
CardItem(
productImg: "https://picsum.photos/250?image=12", productName: "d"),
CardItem(
productImg: "https://picsum.photos/250?image=13", productName: "e"),
CardItem(
productImg: "https://picsum.photos/250?image=14", productName: "f"),
CardItem(
productImg: "https://picsum.photos/250?image=15", productName: "g"),
CardItem(
productImg: "https://picsum.photos/250?image=16", productName: "h")
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: () {},
)
],
backgroundColor: Colors.green,
),
/* drawer: Drawer(
child: AppDrawer(),
),*/
body: SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(),
child: Column(
children: <Widget>[
Container(
height: 200,
width: double.infinity,
child: Text("HomeSlider()"),
),
Padding(
padding: EdgeInsets.only(top: 14.0, left: 8.0, right: 8.0),
child: Text(
'leatest_producrs',
style: TextStyle(
color: Theme.of(context).accentColor,
fontSize: 18,
fontWeight: FontWeight.w700)),
),
Container(
margin: EdgeInsets.symmetric(vertical: 8.0),
height: 200.0,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: cards.length,
itemBuilder: (BuildContext context, int index) => Card(
child: InkWell(
child: Column(
children: [
Flexible(
child: Container(
height: double.infinity,
width: 120,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
cards[index].productImg,
),
fit: BoxFit.fitHeight,
)),
),
),
Container(
width: 150,
padding: EdgeInsets.all(10),
child: Text(cards[index].productName,
style: new TextStyle(fontSize: 12),
softWrap: true),
),
],
),
onTap: () {
},
),
),
),
),
Container(
child: Padding(
padding: EdgeInsets.only(top: 6.0, left: 8.0, right: 8.0),
child: Image(
fit: BoxFit.cover,
image: AssetImage('assets/images/banner-1.jpg'),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0),
child: Text('Featured Products',
style: TextStyle(
color: Theme.of(context).accentColor,
fontSize: 18,
fontWeight: FontWeight.w700)),
),
Padding(
padding: const EdgeInsets.only(
right: 8.0, top: 8.0, left: 8.0),
child: RaisedButton(
color: Theme.of(context).primaryColor,
child: Text('View All',
style: TextStyle(color: Colors.white)),
onPressed: () {
Navigator.pushNamed(context, '/categorise');
}),
)
],
),
Container(
child: GridView.count(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
crossAxisCount: 2,
padding:
EdgeInsets.only(top: 8, left: 6, right: 6, bottom: 12),
children: List.generate(cards.length, (index) {
return Container(
child: Card(
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () {
print('Card tapped.');
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Flexible(
child: Container(
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
cards[index].productImg,
),
fit: BoxFit.fitHeight,
)),
),
),
ListTile(
title: Text(
cards[index].productName,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 12),
)),
],
),
),
),
);
}),
),
),
Container(
child: Padding(
padding: EdgeInsets.only(
top: 6.0, left: 8.0, right: 8.0, bottom: 10),
child: Image(
fit: BoxFit.cover,
image: AssetImage('assets/images/banner-2.jpg'),
),
),
)
],
),
),
)
);
}
}
The Expanded widget has to be a direct child of a Column, Row or Flex. You have it wrapped in a Container. Try to swap the Container and Expanded widgets.

RenderFlex children have non-zero flex but incoming width constraints are unbounded

I am writing code for my news project in flutter.I have copied this code from one tutorial. But I got exceptions and errors in my code. Anybody please help me to solve the issues. My code is:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(97),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 32),
decoration: BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(
width: 0.5,
color: Colors.white,
))),
child: AppBar(
title: Text(
'News',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 30,
),
),
),
// height: 100,
)
]),
),
body: ListView.builder(
itemBuilder: (context, index) {
return _listItem(index);
},
itemCount: _newsInApp.length,
));
}
My console output is:
Launching lib/main.dart on iPhone 11 Pro Max in debug mode...
Running Xcode build...
Xcode build done. 22.9s
Syncing files to device iPhone 11 Pro Max...
flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown during performLayout():
flutter: RenderFlex children have non-zero flex but incoming width constraints are unbounded.
Replace your listItem widget method with :
_listItem(index) {
return Padding(
padding: const EdgeInsets.only(left: 15, top: 1, right: 1, bottom: 1),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.only(bottom: 15),
child: Text(
_newsInApp[index].title,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
),
),
IconButton(
iconSize: 16,
color: Colors.black26,
icon: Icon(Icons.arrow_forward_ios),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) {},
),
),
),
],
),
);
}

Categories

Resources