Developing a Flutter App from 0 to 1
Tags: flutter, ai, mobile, development
Published: 2024-03-05 07:38:47

## 1. Preface
Flutter is an open-source mobile application SDK launched by Google, designed to help developers quickly and efficiently build cross-platform applications. It allows developers to use a single codebase to create high-performance applications that run on iOS, Android, Web, and desktop platforms, greatly improving development efficiency. This article will detail how to start from scratch and develop a Flutter application step by step.

## 2. Flutter Implementation Principles and Technical Details

### 2.1. Dart Language

Flutter chose the Dart language due to its runtime characteristics. Dart supports Just-In-Time (JIT) and Ahead-Of-Time (AOT) compilation. During development, JIT allows for fast compilation and hot reload, while AOT compilation provides optimized, directly compiled native machine code for app releases, meaning Flutter apps can run with near-native performance.

### 2.2. Custom Drawing Engine

Flutter's custom drawing engine is based on the Skia graphics library. Skia is a mature 2D graphics library used for handling low-level drawing operations. Flutter draws UI directly on the Canvas using Skia, instead of using native platform controls. This approach enables Flutter to provide a nearly consistent user experience across different platforms.

### 2.3. Reactive Framework

Flutter's framework is reactive, meaning the UI can dynamically update based on changes in data. Flutter's UI is composed of a series of immutable Widgets that define the structure and appearance of the application. When the application's state changes, the Flutter framework efficiently rebuilds the Widget tree, thus updating the UI.

### 2.4. Rendering Principles

Flutter's rendering process follows these steps:

1. **Layout**: The RenderObject tree performs layout calculations from top to bottom, determining the size and position of each RenderObject.

2. **Painting**: The RenderObject tree paints from bottom to top, with each RenderObject drawing itself on the screen.

3. **Compositing**: Flutter uses layers to optimize the drawing process. Layers are intermediate products in the drawing process that can be cached and reused across multiple frames. When only part of the UI needs to be redrawn, only the changed layers are redrawn, not the entire UI.

#### 2.4.1. Widget Tree

Widgets are the basic building blocks of a Flutter application. Each Widget is an immutable declaration that describes a part of the UI. Widgets can be nested to form a hierarchy, known as the Widget tree. When the application's state changes, Flutter compares the new and old Widget trees and efficiently updates the UI.

#### 2.4.2. Element Tree

Each Widget's position in the Widget tree is represented by an Element object. Element objects are instances of Widgets and are responsible for maintaining the Widget's lifecycle and state. When the Widget tree is rebuilt, the Element tree is updated accordingly.

#### 2.4.3. RenderObject Tree

Behind the Element tree is the RenderObject tree, which is responsible for the actual layout and painting work. RenderObject is an abstract class that defines the layout and painting interface. Each RenderObject knows how to layout and paint itself on the screen.

## 3. Continuously Updated Technology

The Flutter team is constantly updating and improving the framework, with some technologies and features including:

1. **Flutter 2**: Introduced support for Web, desktop, and embedded platforms, making Flutter a truly universal framework.
2. **Flutter Flow**: A low-code development tool that allows developers to quickly create complex Flutter applications.
3. **Flutter Compose**: Integration with Jetpack Compose, simplifying Android development.
4. **Flutter DevTools**: A powerful set of performance analysis and debugging tools to help developers optimize application performance.
5. **Flutter for Web**: Flutter can now be compiled into web applications, using the same UI and business logic code.
6. **Flutter for Desktop**: Supports building desktop applications on Windows, macOS, and Linux.
7. **Flutter for Embedded**: Allows running Flutter applications on embedded devices, such as IoT devices.
8. **New Widgets and Features**: Flutter is constantly adding new Widgets and features.

## 4. Latest Technologies Flutter 3.19 and Dart 3.3

![Flutter 3.19](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/exzqkefk92tmztu7q11a.png)

### 4.1. Flutter 3.19
The Flutter 3.19 version brings a series of new features and improvements, including:

1. Gemini API and Dart SDK updates: Introduced a new Dart SDK that supports Gemini, Google's latest AI model series. Developers can now build generative AI features in Dart or Flutter applications.

2. Impeller rendering performance improvements: Impeller is a new rendering engine for Flutter that enhances rendering performance by using Vulkan and OpenGL backends.

3. Windows Arm64 support: Flutter now supports the Windows Arm64 architecture, providing a more efficient and higher-performance way for Flutter applications to run natively on Windows Arm64 devices.

4. Scrolling improvements: Fixed bugs in SingleChildScrollView and ReorderableList, improved two-dimensional scrolling behavior.

5. AnimationStyle widget: Allows users to override default animation behavior in widgets such as MaterialApp, ExpansionTile, and PopupMenuButton.

6. SegmentedButton.styleFrom method: Quickly create ButtonStyle to configure SegmentedButtonTheme.

7. Adaptive Switch component: Looks and feels native on macOS and iOS, while having a Material Design look and feel on other platforms.

8. SemanticsProperties accessibility identifier: Provides an identifier for semantic nodes in the native accessibility hierarchy.

9. UndoHistory stack improvements: Fixed undo/redo history issues on Japanese keyboards.

10. Performance optimizations on Android and iOS: Includes performance improvements for Impeller's background filters and blur effects.

11. Android deep link web validator: A new tool to help developers validate deep link configurations.

12. Flutter iOS native fonts: Text looks more compact and localized on iOS.

13. DevTools updates: Includes new features and screens for validating deep link settings on Android.

14. Deprecations and breaking changes: Includes ending support for Windows 7 and 8, deprecating iOS 11 support, and more.

The release of Flutter 3.19 once again demonstrates the vitality of the Flutter community and its commitment to innovation. Developers can upgrade to the latest version by running the `flutter upgrade` command to enjoy these new features and improvements.

### 4.2. Dart 3.3

The release of Dart 3.3 brings a series of important new features and improvements, especially in the type system, performance optimization, interaction with native code, and interoperability with JavaScript. Here are some key points of the Dart 3.3 update:

1. **Extension Types**: Dart 3.3 introduces extension types, a compile-time abstraction that allows developers to wrap existing types with different static interfaces without the runtime overhead of actual wrapper objects. This is very useful for optimizing performance when interacting with native platforms.

2. **JavaScript Interop**: Dart 3.3 improves the JavaScript interop model, introducing a type-safe new API `dart:js_interop`. This allows Dart developers to interact with JavaScript code through a typed API, improving the robustness and security of the code.

3. **WebAssembly Support**: Dart 3.3's update paves the way for future support of WebAssembly on the Web platform. Although WebAssembly support in Flutter Web is still experimental, it is a clear direction for Dart and Flutter development.

4. **Improved Browser Libraries**: The Dart SDK has included a comprehensive set of browser libraries, such as `dart:html`, since version 1.0. Now, with the introduction of the new JavaScript calling model, these libraries have the opportunity to be reimagined. Future browser library support will focus on `package:web`, which will simplify version control, accelerate updates, and align with MDN resources.

5. **CanvasKit as the Default Renderer**: According to the "Flutter 2024 Roadmap," CanvasKit will become the default renderer on the Web platform. This means that Dart will adopt the Wasm Native route more on the Web.

6. **Migration to New Libraries**: For developers who want to use WebAssembly to run Flutter applications on the Web, they will need to use the new JavaScript Interop mechanism and `package:web`. The old JavaScript and browser libraries will remain unchanged, but migration will be necessary if compiling to WebAssembly.

These updates to Dart 3.3 show the continuous progress of the Dart language and Flutter framework in improving performance, enhancing type safety, and preparing for future WebAssembly support. Developers can look forward to using these new features in future projects to build more efficient and robust applications.

## 5. Developing a Flutter App

### 5.1. Step 1: Setting Up the Environment

Before you start writing code, you need to set up the Flutter development environment. Here are the basic steps:

1. **Download Flutter SDK**: Visit the Flutter official website (https://flutter.dev) to download the latest version of the Flutter SDK and unzip it to an appropriate directory.
2. **Environment Variable Configuration**: Add the `bin` folder in the Flutter directory to the system's environment variables so that Flutter commands can be accessed from any path.
3. **Install Android Studio or Visual Studio Code**: Both of these IDEs provide good support for Flutter. After installation, you need to install the Flutter and Dart plugins.
4. **Configure Emulator or Real Device for Debugging**: Create an Android emulator in Android Studio or configure real device debugging options.

### 5.2. Step 2: Creating a New Project

Use the following command to create a new Flutter project:

```bash
flutter create my_flutter_app
```

This command will create a project directory with initial Flutter code.

### 5.3. Step 3: Understanding the Project Structure

In the created project, the most important files and directories include:

- `lib/main.dart`: The main entry file of the application.
- `pubspec.yaml`: The project's configuration file for managing dependencies.
- `android` and `ios` directories: Contain platform-specific project files.

### 5.4. Step 4: Writing Your First Flutter Interface

Open the `lib/main.dart` file, and you will see an example Flutter application. This file defines a simple interface, including a title and a button. You can modify this file to create your own interface.

Flutter uses components called "Widgets" to build interfaces. Each Widget is an immutable declaration that describes a part of the interface.

```dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Welcome to Flutter'),
        ),
        body: Center(
          child: Text('Hello World'),
        ),
      ),
    );
  }
}
```

### 5.5. Step 5: Adding Interactivity

Let's add some interactivity to the app. For example, we can add a button that, when clicked, displays a message.

```dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Text(
          'You have pushed the button this many times: $_counter',
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
```

In this example, we created a `StatefulWidget` with a state variable `_counter` that increments each time the button is clicked. The `setState` method triggers a rebuild of the interface to reflect the new state.

### 5.6. Step 6: Adding Dependencies and External Libraries

In the `pubspec.yaml` file, you can add dependencies for third-party libraries. For example, if you want to add a networking library like `http`, you can add the following content to `pubspec.yaml`:

```yaml
dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3
```

Then run `flutter pub get` to install the dependencies.

### 5.7. Step 7: Running and Debugging

Use the run button in the IDE or enter `flutter run` in the command line to start the app. You can see the app running on the emulator or real device.

During development, you can use Flutter's hot reload feature to quickly see your changes. Just make changes in the code and save the file, and the app will automatically update.

### 5.8. Step 8: Packaging and Publishing

When your app is ready for release, you can use the following commands to package your app:

- For Android: `flutter build apk`
- For iOS: `flutter build ios`

## 6. Developing a Flutter App from Scratch with Codia AI Code
To integrate Codia AI into your Figma to Flutter development process, follow these instructions:
Open the link: [Codia AI Figma to code: HTML, CSS, React, Vue, iOS, Android, Flutter, ReactNative, Tailwind, Web, App](https://codia.ai/s/YBF9)

![Codia AI Figma to code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/inv8hm9xseb5ahjjy3hu.png)

- Install the Codia AI Plugin: Search for and install the Codia AI Figma to Flutter plugin from the Figma plugin store.
- Prepare Your Figma Design: Arrange your Figma design with clearly named layers and components to ensure the best code generation results.
- Convert with Codia AI: Select your design or component in Figma and use Codia AI to instantly 

![install plugin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsyx29dhx4qug4pmszsz.png)

generate Flutter code.

![Flutter code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uwz900nu9vp8tnth0bm5.png)