Skybinary

View Categories

1. Flutter Widget Fundamentals

1 min read

Flutter Widget Fundamentals #

Goal: Understand the building blocks of Flutter — everything in Flutter’s UI is built from widgets.

1. Widget Tree (Everything is a Widget) #

Flutter’s entire UI is structured as a Widget Tree, where every element (text, image, button, layout) is a widget.
Each widget describes what its view should look like, and Flutter efficiently rebuilds only parts that change.

  • Example hierarchy:
    MaterialApp → Scaffold → Column → Text / Button
  • Widgets are nested, forming a tree that defines layout and behavior.
  • Parent widgets control layout; child widgets define content.

2. StatelessWidget vs StatefulWidget #

These are the two main types of widgets in Flutter:

1) StatelessWidget:

  • Immutable — once built, cannot change dynamically.
  • Used for static content that doesn’t update (e.g., icons, labels).
  • Example:
class MyText extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text("Hello Flutter!");
  }
}

2) StatefulWidget:

  • Mutable — can change during runtime.
  • Maintains a State object that updates the UI when data changes.
  • Example:
class CounterApp extends StatefulWidget {
  @override
  _CounterAppState createState() => _CounterAppState();
}

class _CounterAppState extends State<CounterApp> {
  int count = 0;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text("Count: $count"),
        ElevatedButton(
          onPressed: () => setState(() => count++),
          child: Text("Increment"),
        ),
      ],
    );
  }
}

3. BuildContext & Element Tree #

  • BuildContext represents the location of a widget in the widget tree.
  • It helps widgets access information from their ancestors (e.g., Theme, MediaQuery).
  • Example: Theme.of(context).textTheme;
  • Flutter maintains an Element Tree under the hood — it connects the Widget Tree (blueprint) to the Render Tree (actual layout).

4. setState() & Rebuilding #

  • setState() notifies Flutter that the widget’s internal state has changed.
  • When called, Flutter rebuilds only the affected widget subtree — not the entire UI.
  • Best practice: Keep rebuild areas small for better performance.

Example:

setState(() {
  count++;
});

This triggers the build() method again to refresh the UI with updated data.

Powered by BetterDocs

Leave a Reply

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

Scroll to Top