Topic: 1 Understanding Flutter

This is our first topic from the new series Learn Flutter: Basic to Advance

Β·

7 min read

Topic: 1 Understanding Flutter

Hello devs, So this is our first topic from the Learn Flutter: Basic to Advance Series. In our first topic, we discussed what is Flutter, what is hot reload and hot restart in Flutter, and talked about widgets in Flutter. To create a flutter app we use Dart language.

Flutter

Flutter is an open-source UI software development kit (SDK) created by Google. It is used for developing cross-platform applications for mobile, web, and desktop from a single codebase. Flutter allows developers to write code once and deploy it across multiple platforms, which saves time and effort.

With the help of Flutter, we create Applications for both platform Android and iOS in a single code base. In Flutter there are two best features are there :

  1. HotReload

  2. HotRestart

Alright, devs Let's discuss this feature one by one.

HotReload

Hot reload is a feature in Flutter that allows developers to instantly see the changes they make to their code reflected in the running application without needing to restart or lose the app's state. It's like having a live connection between your code editor and the running app.

Here's how it typically works in practice:

  1. Make Code Changes: As a developer, I write or modify code in my preferred code editor (e.g., Visual Studio Code, IntelliJ IDEA).

  2. Save Changes: After making the desired changes, I save the file.

  3. Instant Update: With hot reload enabled, Flutter injects the updated code into the running app, and the changes are immediately reflected in the app's UI. This process happens almost instantaneously, usually within a second or less.

  4. Keep State: Notably, hot reload preserves the app's state during the update. This means that if I'm in the middle of interacting with the app, such as filling out a form or navigating through screens, I can continue seamlessly after the code changes are applied.

  5. Iterative Development: With hot reload, I can iterate rapidly, making small adjustments to the code and seeing the results in real-time. This facilitates a faster development cycle and allows for quicker experimentation and debugging.

  6. Debugging: Hot reload is also invaluable for debugging. I can make changes to the code to fix bugs, and immediately see if the changes have the desired effect, without the need to pause or restart the debugging session.

Overall, hot reload is a game-changer for Flutter development. It promotes productivity, enables faster iteration, and provides an immersive development experience by bridging the gap between code and UI in real-time.

HotRestart

Hot restart is a feature in Flutter that allows developers to quickly rebuild the entire app and restart it from scratch while maintaining the app's current state. It's similar to hot reload, but instead of injecting updated code into the running app, hot restart completely refreshes the app, loading the latest changes from the source code.

Here's how hot restart works in practice:

  1. Make Code Changes: Like with hot reload, I make changes to the code in my preferred code editor.

  2. Save Changes: After making the desired changes, I save the file.

  3. Trigger Hot Restart: Unlike hot reload, which injects code changes into the running app, I trigger a hot restart by pressing a specific command or button (e.g., "R" in the terminal or clicking the restart button in an IDE like Visual Studio Code). This action rebuilds the entire app from scratch.

  4. Rebuild and Restart: During a hot restart, Flutter rebuilds the entire app, recompiles the code, and restarts the app with the latest changes. This process takes slightly longer than hot reload because it involves reloading the entire app, but it's still much faster than a full cold restart.

  5. Preserve State: One of the key advantages of a hot restart is that it preserves the app's current state. This means that if I'm in the middle of using the app, such as filling out a form or navigating through screens, the app will restart with all the current data and UI state intact.

  6. Debugging and Testing: Hot restart is particularly useful for testing changes that affect the app's initialization process or require a full reset. It's also helpful for debugging certain issues that may not be easily resolved with hot reload alone.

Overall, hot restart is a valuable tool for Flutter developers, providing a quick way to apply code changes and see the results in the context of a fresh app instance while maintaining the app's current state. It complements hot reload by offering a more comprehensive refresh mechanism when needed.

Ok devs, Now it's time to dive into the Widgets. widgets are the building blocks of the user interface (UI). They define the layout, appearance, and behavior of elements in the app. Basically, in Flutter, there are two types of widgets are available.

  1. Stateless Widgets

  2. StateFul Widgets

Alright devs, Let's talk about these widgets one by one.

Stateless Widgets

A stateless widget is a type of widget in Flutter that does not have a mutable state. This means that once created, the properties of a stateless widget cannot change. Stateless widgets are immutable, which means their properties, such as size, color, and text, are set when the widget is created and cannot be modified after that.

Stateless widgets override the build method to define their UI. The build method returns a widget tree that describes the widget's UI, usually by composing other widgets.

When the parent widget requests to rebuild or when there are changes in the widget's context (such as device orientation changes) the Stateless widgets are rebuilt. Flutter calls the build method again to recreate the widget's UI.

Stateless widgets are lightweight because they do not need to manage any internal state. Stateless widgets are commonly used for UI elements that do not change over time or do not depend on any external state. Examples include buttons, icons, labels, and static content.

import 'package:flutter/material.dart';

class MyButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;

  const MyButton({required this.text, required this.onPressed});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(text),
    );
  }
}

In this example, MyButton is a stateless widget representing a button. It takes two parameters, text (the button label) and onPressed (the callback function when the button is pressed). The build method creates an ElevatedButton widget with the provided text and onPressed callback. Since MyButton is stateless, its properties cannot change after instantiation.

Stateful Widgets

A stateful widget is a type of widget in Flutter that can hold a mutable state. This allows the widget to update its appearance or behavior dynamically in response to user actions, changes in data, or other events.

Every stateful widget is associated with a corresponding state object. The state object is responsible for holding the mutable state data and implementing the widget's logic.

Stateful widgets override lifecycle methods like createState, initState, dispose, and didUpdateWidget to manage the lifecycle of their state objects. These methods allow developers to initialize the state, perform cleanup operations, and respond to changes in widget properties.

Like stateless widgets, stateful widgets also override the build method to define their UI. The build method is called whenever the widget needs to rebuild its UI due to changes in state or other factors.

The primary mechanism for updating state in a stateful widget is the setState method. When called, setState notifies Flutter's framework that the widget's state has changed, triggering a rebuild of the widget's UI. This allows developers to update the UI in response to user interactions or other events.

Stateful widgets are used when the UI needs to change dynamically based on user input, data changes, or other factors. Examples include forms, interactive elements like buttons and switches, and widgets displaying real-time data.

import 'package:flutter/material.dart';

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Counter Widget'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Counter Value:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

In this example, CounterWidget is a stateful widget that maintains a mutable _counter state variable. When the floating action button is pressed, _incrementCounter is called to update the counter value using setState, triggering a rebuild of the widget's UI to reflect the updated state.

Alright devs, So this is the end of the blog. In the next blog, we deeply understand about different types of widgets that are used in Flutter UI and also understand the stateful widget lifecycle.


Connect with Me:

Hey there! If you enjoyed reading this blog and found it informative, why not connect with me on LinkedIn? 😊 You can also follow my Instagram page for more mobile development-related content. πŸ“²πŸ‘¨β€πŸ’» Let’s stay connected, share knowledge and have some fun in the exciting world of app development! 🌟

Check out my Instagram page

Check out my LinkedIn

Β