To create a custom widget in Flutter, you can extend the StatelessWidget or StatefulWidget class, depending on whether the widget has mutable state or not.
Here's an example of a custom stateless widget:
class MyCustomWidget extends StatelessWidget {
final String text;
MyCustomWidget({this.text});
@override
Widget build(BuildContext context) {
return Text(text);
}
}
To use this widget, you can simply include it in your widget tree like any other widget:
MyCustomWidget(text: "Hello, world!")
If you want to create a custom stateful widget, you can extend the StatefulWidget class and create a corresponding State class:
class MyCustomWidget extends StatefulWidget {
final String text;
MyCustomWidget({this.text});
@override
_MyCustomWidgetState createState() => _MyCustomWidgetState();
}
class _MyCustomWidgetState extends State<MyCustomWidget> {
String _text;
@override
void initState() {
_text = widget.text;
super.initState();
}
void updateText(String newText) {
setState(() {
_text = newText;
});
}
@override
Widget build(BuildContext context) {
return Text(_text);
}
}
To use this widget, you can include it in your widget tree like any other widget, and use the updateText method to update the widget's state:
MyCustomWidget(text: "Hello, world!")
myCustomWidget.updateText("Goodbye, world!");
I hope this helps! Let me know if you have any questions.