I have created a simple shopping app. Im trying to show a snackbar on the main home screen when a user adds a product to the cart. The HomeScreen has a ListView.builder that builds the list. Each child of this builder directs to a ItemDetailsScreen using a Navigator.pop() which listens to a pop using the Future thats being returned by the Navigator.push(). A simple Scaffold.of(context).showSnackBar() is used in the then() statement. Unfortunately an error is being thrown as such:
Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe. At this point the state of the widget's element tree is no longer stable.To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
Below is the code -
home_screen.dart:
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
final _scaffoldKey = GlobalKey<ScaffoldState>();
return Scaffold(
key: _scaffoldKey,
backgroundColor: Theme.of(context).primaryColor,
drawer: AppDrawer(),
body: Column(
.......
Flexible(
flex: 4,
child: Container(child: ItemList()),
),
)
item_list.dart:
Widget build(BuildContext context) {
final items = Provider.of<List<Item>>(context);
if (items != null) {
return ListView.builder(
itemBuilder: (context, index) => ChangeNotifierProvider.value(
// Value should be used in grids or lists because of the widget being destroyed and reference being empty issue
value: items[index],
child: ItemListTile(),
),
itemCount: items.length,
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
}
item_list_tile.dart:
@override
Widget build(BuildContext context) {
final item = Provider.of<Item>(context);
final cart = Provider.of<Cart>(context, listen: false);
return Padding(
padding: EdgeInsets.only(top: 10.0),
child: InkWell(
onTap: () {
Navigator.of(context)
.push(
MaterialPageRoute(
builder: (context) => ItemDetailsScreen(
itemId: item.id,
itemName: item.name,
itemPrice: item.price,
imageUrl: item.imageUrl,
),
),
)
.then((_) => Scaffold.of(context)
.showSnackBar(SnackBar(content: Text("Item added"))));
},
ItemDetailsScreen (where the user adds the item to the cart and the screen is popped to go back to the home screen):
Padding(
padding: EdgeInsets.only(bottom: 5.0),
child: InkWell(
onTap: () {
cart.addToCart(
widget.itemId,
widget.itemPrice,
widget.itemName,
widget.imageUrl,
numberOfItems,
);
Navigator.of(context).pop();
},
I have tried using the Builder widget and Global keys as well with no luck. Any idea what I'm doing wrong here?