Open In App

How to Create Private Class in Dart?

Last Updated : 08 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we see how we can make the private class in dart. You know how to make the public class in dart. Here is the syntax for making the public class in the dart language.

Public class syntax:

class class_name {
  // Body of class
}

Now we will see how you can make the private class in the dart. For making the private class in dart we simply need to add the underscore at the start of the class name as you can see in the syntax.

Private class syntax:

class _class_name {
 // Body of class
}

Code Of Public Class

Dart




// ignore_for_file: prefer_const_constructors
  
import 'package:flutter/material.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Geeks For Geeks',
      theme: ThemeData(
        primarySwatch: Colors.green,  
      ),
      home: MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  
  @override
  State<MyHomePage> createState() => MyHomePageState();
}
  
class MyHomePageState extends State<MyHomePage> {
                
  @override
  Widget build(BuildContext context) {
      
    return Text("Hello Geeks");
  }
}


Output:

Hello Geeks

Code Of Private Class

Dart




// ignore_for_file: prefer_const_constructors
  
import 'package:flutter/material.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Geeks For Geeks',
      theme: ThemeData(
        primarySwatch: Colors.green,  
      ),
      home: MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
                
  @override
  Widget build(BuildContext context) {
      
    return Text("Hello Geeks");
  }
}


Output:

Hello Geeks

Explanation:

Here you can see the output is the same for both codes what is the meaning to make the private class, You can see in public we can access data from anywhere in the code but in a private class, you can not access the data from anywhere or you can say globally. Private class data is only accessed by their parent class. so you can say that private class provides security to data that is not accessed by anyone. This is the reason to make the private class and private class are mostly used.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads