ERROR:flutter/lib/ui/ui_dart_state.cc(209)未处理异常:在dispose()之后



我面临[ERROR:flutter/lib/ui/ui_dart_state.cc(209)]未处理异常:dispose()后调用setState(): _AddToCardWidgetState#c0593(生命周期状态:defunct,未安装)错误打印为:

This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter (26736): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter (26736): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter (26736): #0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1085:9)
E/flutter (26736): #1      State.setState (package:flutter/src/widgets/framework.dart:1120:6)
E/flutter (26736): #2      _AddToCardWidgetState.build.<anonymous closure>.<anonymous closure> (package:multi_vending_grocery_app/widgets/products/add_to_cart_widget.dart:57:11)
E/flutter (26736): #3      List.forEach (dart:core-patch/growable_array.dart:433:8)
E/flutter (26736): #4      _AddToCardWidgetState.build.<anonymous closure> (package:multi_vending_grocery_app/widgets/products/add_to_cart_widget.dart:55:26)
E/flutter (26736): #5      _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter (26736): <asynchronous suspension>

请求同胞flutter和dart开发人员帮助我解决这个问题。当我从AddToCardWidget更改产品数量值并导航回ProductListWidget时,数量值不会在那里更新,而是在我的android studio控制台显示上面解释的错误。帮我修理一下,我是新来的,所以不能独自解决它。

AddToCardWidget代码

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:multi_vending_grocery_app/services/cart_services.dart';
import 'package:multi_vending_grocery_app/widgets/cart/counter_widget.dart';
class AddToCardWidget extends StatefulWidget {
const AddToCardWidget({Key? key, this.documentSnapshot}) : super(key: key);
final DocumentSnapshot? documentSnapshot;
@override
State<AddToCardWidget> createState() => _AddToCardWidgetState();
}
class _AddToCardWidgetState extends State<AddToCardWidget> {
final CartServices _cartServices = CartServices();
User? user = FirebaseAuth.instance.currentUser;
bool isLoading = true;
bool exists = false;
int _qty = 1;
String? _docId;
@override
void initState() {
getCartData();
super.initState();
}
getCartData() async {
final snapshot =
await _cartServices.cart.doc(user?.uid).collection('products').get();
if (snapshot.docs.isEmpty) {
setState(() {
isLoading = false;
});
} else {
setState(() {
isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
//If Product exist in car , we need to get qty details
FirebaseFirestore.instance
.collection('cart')
.doc(user?.uid)
.collection('products')
.where('productId', isEqualTo: widget.documentSnapshot?['productId'])
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
if (doc['productId'] == widget.documentSnapshot?['productId']) {
setState(() {
exists = true;
_qty = doc['qty'];
_docId = doc.id;
});
}
});
});
return isLoading
? Container(
height: 56,
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).primaryColor),
),
),
)
: exists
? CounterWidget(
documentSnapshot: widget.documentSnapshot,
qty: _qty,
docId: _docId.toString(),
)
: InkWell(
onTap: () {
EasyLoading.show(status: "Adding Product To Cart");
_cartServices
.addToCart(widget.documentSnapshot)
.then((value) {
setState(() {
exists = true;
});
EasyLoading.showSuccess("Added to Cart");
});
},
child: Container(
height: 56,
color: Colors.red[400],
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(
CupertinoIcons.shopping_cart,
color: Colors.white,
),
SizedBox(
width: 10,
),
Text(
"Add to Basket",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),
),
],
)),
),
),
);
}
}
ProductListWidget代码
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:multi_vending_grocery_app/providers/store_provider.dart';
import 'package:multi_vending_grocery_app/services/product_services.dart';
import 'package:multi_vending_grocery_app/widgets/products/product_card_widget.dart';
import 'package:provider/provider.dart';
class ProductListWidget extends StatelessWidget {
const ProductListWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
ProductServices _services = ProductServices();
var _storeProvider = Provider.of<StoreProvider>(context);
return FutureBuilder<QuerySnapshot>(
future: _services.products
.where('published', isEqualTo: true)
.where('categoryName.mainCategory',
isEqualTo: _storeProvider.selectedProductCategory)
.where('categoryName.subCategory', isEqualTo: _storeProvider.selectedSubCategory)
.where('seller.sellerUid',
isEqualTo: _storeProvider.storeDetails?['uid'])
.get(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return const Text("Something Went Wrong");
}
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
}
return Column(
children: [
Material(
elevation: 4,
borderRadius: BorderRadius.circular(4),
child: Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 10),
child: Text(
"${snapshot.data.docs.length} Items",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.grey[600],
fontSize: 18),
),
)
],
),
),
decoration: BoxDecoration(
color: Colors.grey[400],
borderRadius: BorderRadius.circular(4)),
height: 56,
),
),
ListView(
padding: EdgeInsets.zero,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
children:
snapshot.data.docs.map<Widget>((DocumentSnapshot document) {
return ProductCard(documentSnapshot: document);
}).toList(),
)
],
);
},
);
}
}

移动代码块

FirebaseFirestore.instance
.collection('cart')
.doc(user?.uid)
.collection('products')
.where('productId', isEqualTo: widget.documentSnapshot?['productId'])
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
if (doc['productId'] == widget.documentSnapshot?['productId']) {
setState(() {
exists = true;
_qty = doc['qty'];
_docId = doc.id;
});
}
});
});

initState而不是build,这是因为你在构建方法中是settingState,这可能发生在"构建框架"期间;会导致你遇到的问题的进程

将代码块移到initState可能会解决你的问题

相关内容

最新更新