Stateful Widgets

Jun's Coding Journey·2023년 8월 16일
0

[Learn] Flutter

목록 보기
5/22

State


What is State?

In Flutter, a "state" refers to the data that can change over time and affect the appearance or behavior of the user interface. Flutter follows a reactive programming model where the UI is automatically updated when the underlying state changes.

Stateless Widget

This is a widget that doesn't have any mutable state. It simply builds the UI based on the input it receives via its constructor (properties or parameters). Stateless widgets are ideal for UI components that don't change over time.

Stateful Widget

This is a widget that can maintain mutable state. It consists of two classes:

  • The first class, which extends StatefulWidget, is responsible for creating an instance of the second class.
  • The second class, which extends State, holds the mutable state that can change over time. This is where you put the logic that can modify the state.

When the state in a StatefulWidget changes, the associated State object is rebuilt, and the UI is updated accordingly. This process is automatic and follows the principle of reactive programming.

setState

In Flutter, setState is a method provided by the State class in a StatefulWidget. It is used to signal the framework that the internal state of the widget has changed and that the UI needs to be rebuilt to reflect those changes. Essentially, setState is used to update the state of a StatefulWidget and trigger a rebuild of its associated UI.

  • When you call setState, you provide a callback function that updates the mutable state within the State object.
  • The framework then schedules a rebuild of the widget's UI.
  • During the rebuild, the widget's build method is called, and the updated state is used to build the new UI.
// Example
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CounterWidget(),
    );
  }
}

class CounterWidget extends StatefulWidget {
  
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter App')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Counter:', style: TextStyle(fontSize: 24)),
            Text('$_counter', style: TextStyle(fontSize: 48)),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

 

BuildContext


BuildContext is a fundamental concept that represents the location of a widget within the widget tree. It provides a way for widgets to reference and interact with other widgets and resources in the application.

BuildContext is passed as an argument to the build method of a widget, which is responsible for creating and returning the widget's UI representation. This context is important because it carries information about the widget's position in the widget tree, such as its parent and its position relative to other widgets.

In order to access contexts of other widgets, we use the following method:

Theme.of(context).{code you want to access}
// Example
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.blue,
        accentColor: Colors.orange,
        fontFamily: 'Roboto',
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Theme Example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Primary Color',
              style: TextStyle(
                color: Theme.of(context).primaryColor,
                fontSize: 24,
              ),
            ),
            SizedBox(height: 20),
            Text(
              'Accent Color',
              style: TextStyle(
                color: Theme.of(context).accentColor,
                fontSize: 24,
              ),
            ),
            SizedBox(height: 20),
            Text(
              'Custom Font',
              style: TextStyle(
                fontFamily: Theme.of(context).textTheme.bodyText1!.fontFamily,
                fontSize: 24,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

 

Widget Lifecycle


A widget's lifecycle refers to the sequence of events that occur during its existence, from its creation to its removal. Understanding the widget lifecycle is essential for managing state, performing side effects, and optimizing performance in your Flutter applications.

3 Basic State Methods:

  • State.initState: This method is called when the State object is created. It's the right place for initializing state variables that won't change during the widget's lifetime.
void initState() {
  super.initState();
  // your code
}
  • State.build: This is where the actual UI representation of the widget is built. The build method should be pure and not involve changing the widget's state. It's called every time the widget needs to be rebuilt, which can happen due to changes in the widget's state or other factors.
// your build code
  • State.dispose: This is the cleanup phase. When the widget is no longer needed, the dispose method is called. It's where you should release resources, unsubscribe from streams, and perform any necessary cleanup.
void dispose() {
  super.dispose();
  // your code
}

Most of the time, these methods are not used unless we need to initialize data from the parent widget or from an outside API.


profile
Greatness From Small Beginnings

1개의 댓글

comment-user-thumbnail
2023년 8월 16일

유익한 자료 감사합니다.

답글 달기