Question #17MediumDart Basics

Create private variable inside constructor

Answer

Overview

In Dart, private variables are prefixed with an underscore

text
_
. You can initialize them directly in a constructor while keeping them private to the class/library.


Private Variables via Constructor

dart
class BankAccount {
  // Private fields — underscore prefix
  final String _accountId;
  double _balance;
  final String _owner;

  // Constructor initializes private fields
  BankAccount({
    required String accountId,
    required String owner,
    double initialBalance = 0.0,
  }) : _accountId = accountId,
       _owner = owner,
       _balance = initialBalance;

  // Public getters — controlled access
  String get accountId => _accountId;
  String get owner => _owner;
  double get balance => _balance;

  void deposit(double amount) {
    if (amount > 0) _balance += amount;
  }

  void withdraw(double amount) {
    if (amount > 0 && amount <= _balance) _balance -= amount;
  }
}

void main() {
  final account = BankAccount(accountId: 'ACC001', owner: 'Alice', initialBalance: 1000);
  print(account.balance); // 1000.0 ✅ via getter
  // print(account._balance); // ❌ Error (in a different file) — private!
  account.deposit(500);
  print(account.balance); // 1500.0
}

Shorthand Constructor with Private Fields

dart
class Counter {
  int _count; // private

  // Direct assignment in constructor body
  Counter(int initialValue) : _count = initialValue;

  // Or initialize in body
  Counter.fromZero() : _count = 0;

  void increment() => _count++;
  int get count => _count;
}

Private in Dart — Library-Level Privacy

⚠️ In Dart,

text
_
makes fields library-private (not class-private). Code in the same file CAN access
text
_
fields.

dart
// file: bank_account.dart
class BankAccount {
  double _balance = 0; // Private to this file/library
}

// Same file — can access _balance
void resetAccount(BankAccount acc) {
  acc._balance = 0; // ✅ Same library — accessible
}

// Another file — cannot access _balance
import 'bank_account.dart';
final acc = BankAccount(...);
// acc._balance = 0; // ❌ Error — different library

Named Constructor with Private Initialization

dart
class Config {
  final String _apiUrl;
  final String _apiKey;
  final int _timeout;

  Config._({
    required String apiUrl,
    required String apiKey,
    int timeout = 30,
  }) : _apiUrl = apiUrl,
       _apiKey = apiKey,
       _timeout = timeout;

  // Factory that uses private constructor
  static Config? _instance;
  factory Config.getInstance() {
    _instance ??= Config._(
      apiUrl: 'https://api.example.com
      apiKey: 'my-secret-key',
    );
    return _instance!;
  }
}

Key Point: Prefix with

text
_
to make a field private. Use constructor initializer lists (
text
: field = value
) to initialize private final fields. Expose state through public getters and controlled mutation methods.