Flutter Dart Constructor Method with Example
The constructor is like a function with or without parameter but it doesn’t have a return type. That's why you can create new object using this constructor. In this tutorial we will discuss about how to use constructor and as a bonus we also provide you a great tool to generate constructor.
Now you can create new object using this Student constructor.
Constructor in Dart
There are many types of Constructors that you will need to know when working with Dart class. For example, this is Student class with constructor that has the same name:
class Student {
String name;
int age;
String location;
// constructor
Customer(String name, int age, String location) {
this.name = name;
this.age = age;
this.location = location;
}
}
Now you can create new object using this Student constructor.
var student = Student("Jhon Wick", 26, "US");
Constructor in Flutter
We know constructor dosen't have any return type , that's why it can be used to transfer variable from one widget to another. You can also pass variable from stateless widget into statefull widget using constructor method. Let us give you an example.
Passing Data into Widget
Create a new stateless widget. Then create a constructor as we create before. Here key is by default. For understanding easily, take it as screen 2.
import 'package:flutter/material.dart';
class Student extends StatelessWidget {
String name;
int age;
String location;
//constructor
Student({
Key? key,
required this.name,
required this.age,
required this.location,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(name),
Text(age.toString()),
Text(location)
],
);
}
}
Now suppose you have another widget, take it as Screen 1. It's hold our actual variable which we want to show in this Student widget (Screen 2). When user click on a button of Screen 1, it will show the information in (Screen 2) . Navigator.push is used to change Screens in our App. So our Screen 1 will be this.class Screen1 extends StatelessWidget {
const Screen1({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: TextButton(
onPressed:() {
Navigator.push( context,
MaterialPageRoute(builder: (context) => Student(name: 'Jhon Wick',age: 26,location: 'US',)),
);
},
child: const Text('View Details'),
));
}
}
Constructor Maker Extension
Developers are smart. To make your works more productive you can try this Constructor Generator Extension on VS Code.
Conclusion
In this tutorial you’ve learned about Constructors in Dart/Flutter and How constructor uses in Flutter to pass data from one screen to another. There are also many constructor on Dart. Such as Dart Named constructor, Factory constructor etc. As a beginner hope it will help you to easily understand the concept.
Happy Learning! See you again.