How to create custom widget in flutter
- Create a new flutter project. Head to the terminal, navigate to your project directory and create a new flutter project with the command below:
flutter create nameofyourproject
2. Open the project, lib/main.dart file, remove all the default code, retain only the void main() function, MyApp class which returns a MaterialApp.
//it should look like this
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Custom Widget',
home: StartPage(),
);
}
}
the home parameter of your Material App should be a Stateless or Stateful widget, you can call it anything, i call mine StartPage() which returns a Scaffold
// here is the full snipet of how will look like after adding the startpage which is a statelesswidget
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Custom Widget',
home: StartPage(),
);
}
}
//this is where you create your statelesswidget for the startpage
class StartPage extends StatelessWidget {
const StartPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold();
}
}
When you add appbar title, and body with Text(‘My Custom Widget’) and center widget you will get this on the simulator.
3. Next, We would declare the custom widget using the Widget keyword. Return any flutter widget of our choice inside it, in this case i am using Container with child Text, and replace the child widget in the body Center, with our custom widget
//put the myCustomWidget in the body like so
return Scaffold(
appBar: AppBar(
title: Text('My Custom Widget'),
),
body: Center(
child: myCustomWidget(),
),
);
// create your custom widget like so
Widget myCustomWidget() {
return Container(
width: 200,
height: 150,
color: Colors.pinkAccent,
child: Text('Custom Widget'),
);
}
see the output
you can put any flutter widget in this custom widget wrap as many as you want, see the full code below:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Custom Widget',
home: StartPage(),
);
}
}
//this is where you create your stateellesswidget for the startpage
class StartPage extends StatelessWidget {
const StartPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Custom Widget'),
),
body: Center(
child: myCustomWidget(),
),
);
}
}
// to create the custom widget
Widget myCustomWidget() {
return Container(
width: 200,
height: 150,
color: Colors.pinkAccent,
child: Text('Custom Widget'),
);
}
Hope this was helpful…