Here is the solution which worked for me.
OUTPUT: State of Cart Widget is updated, upon addition of items.
Create a globalKey
for the widget you want to update by calling the trigger from anywhere
final GlobalKey<CartWidgetState> cartKey = GlobalKey();
Make sure it's saved in a file have global access such that, it can be accessed from anywhere. I save it in globalClass where is save commonly used variables through the app's state.
class CartWidget extends StatefulWidget {
CartWidget({Key key}) : super(key: key);
@override
CartWidgetState createState() => CartWidgetState();
}
class CartWidgetState extends State<CartWidget> {
@override
Widget build(BuildContext context) {
//return your widget
return Container();
}
}
Call your widget from some other class.
class HomeScreen extends StatefulWidget {
HomeScreen ({Key key}) : super(key: key);
@override
HomeScreenState createState() => HomeScreen State();
}
class HomeScreen State extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return ListView(
children:[
ChildScreen(),
CartWidget(key:cartKey)
]
);
}
}
class ChildScreen extends StatefulWidget {
ChildScreen ({Key key}) : super(key: key);
@override
ChildScreenState createState() => ChildScreen State();
}
class ChildScreen State extends State<ChildScreen> {
@override
Widget build(BuildContext context) {
return InkWell(
onTap: (){
// This will update the state of your inherited widget/ class
if (cartKey.currentState != null)
cartKey.currentState.setState(() {});
},
child: Text("Update The State of external Widget"),
);
}
}