Flutter Private Properties

Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore _, it’s private to its library. Libraries not only provide APIs, but are a unit of privacy: identifiers that start with an underscore _ are visible only inside the library.

Every Dart app is a library, even if it doesn’t use a library directive. The import and library directives can help you create a modular and shareable code base.

//File Name: main.dart
import 'package:flutter/material.dart';

* The arrow function allows us to create a simplified function consisting of a single expression.
* We can omit the curly brackets and the return keyword

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
   * createState() is a method that takes no arguments but returns a State object
   * which is connected to a StatefulWidget
  State<StatefulWidget> createState() {
    return _MyAppState();
  } //createState()
} //StatefulWidget

/* A leading underscore makes the property private, here leading underscore will turn
 * this public class in to private class. Now MyAppState class can only be used in
 * main.dart file, in our case in MyApp class.
class _MyAppState extends State<MyApp>{
  var _questionIndex = 0;

  void _answerQuestion() {
    setState( () {
    } );

  Widget build(BuildContext context) {
    var questions = [
      'What\'s your favorite color?',
      'What\'s your favorite animal?'
    return MaterialApp(
      * A Scaffold Widget provides a framework which implements the basic material design visual
      * layout structure of the flutter app.
      home: Scaffold(
        appBar: AppBar(
          title: Text('First Flutter App'),
        body: Column(
          children: <Widget>[
              child: Text('Answer1'),
              //onPressed takes a function
              onPressed: _answerQuestion,
              child: Text('Answer2'),
              onPressed: () => print('Answer2 chosen!'),
              child: Text('Answer3'),
              onPressed: () {
                //...multiline function body
                print('Answer3 chosen');
  } //build()
} //MyApp()



Happy Coding!



no responses for Flutter Private Properties

    Leave a Reply

    Your email address will not be published. Required fields are marked *