So basically you want to call methods of your CustomWidget from another widget. You can define ControllerClass that you will emit an instance when you create a new instance of your CustomWidget. This ControllerClass instance will hold the functions of your CustomWidget and you will be able to call them from outside.
By example a class that is a modal rounded progressbar that can be showed and hided from outise with a controller class. In this example a controller class is called ProgressBarHandler. I don't know if it is a better and the right approach but works.
class ModalRoundedProgressBar extends StatefulWidget {
final String _textMessage;
final double _opacity;
final Color _color;
final Function _handlerCallback;
ModalRoundedProgressBar({
@required Function handleCallback(ProgressBarHandler handler), //callback to get a controller
String message = "",
double opacity = 0.7,
Color color = Colors.black54,
}) : _textMessage = message,
_opacity = opacity,
_color = color,
_handlerCallback = handleCallback;
@override
State createState() => _ModalRoundedProgressBarState();
}
class _ModalRoundedProgressBarState extends State<ModalRoundedProgressBar> {
bool _isShowing = false;
@override
void initState() {
super.initState();
// init controller.
ProgressBarHandler handler = ProgressBarHandler();
handler.show = this.show;
handler.dismiss = this.dismiss;
widget._handlerCallback(handler); // callback call.
}
@override
Widget build(BuildContext context) {
if (!_isShowing) return Stack();
return Material(
color: Colors.transparent,
child: Stack(
children: <Widget>[
Opacity(
opacity: widget._opacity,
child: ModalBarrier(
dismissible: false,
color: Colors.black54,
),
),
Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
Text(widget._textMessage),
],
),
),
],
),
);
}
void show() {
setState(() => _isShowing = true);
}
void dismiss() {
setState(() => _isShowing = false);
}
}
class ProgressBarHandler {
Function show; // will point to widget show method
Function dismiss; // will point to another method.
}
// ...in another external widget you can do...
// ... code your things and:
var controller;
var progressBar = ModalRoundedProgressBar(
handleCallback: ((handler){ controller = handler; } ),);
//calling show method with controller
RaisedButton(
onPressed: () { controller.show(); }
);
//calling dismiss method with controller
RaisedButton(
onPressed: () { controller.dismiss(); }
);