Share 7 useful Flutter libraries to make your development life easier

46079696f8891d56977c4edcae34b127.jpeg

Make your Flutter development more efficient

8906a6e94dffe6cde7071bf9a56f329c.jpeg

Why write custom functionality when you can use a library? Libraries are a developer's best friend and lifesaver. In my opinion, a good project should take advantage of some of the best available libraries.

In this article, part of a series on awesome libraries in Flutter, I've rounded up 7 Flutter libraries that will help you move forward in your development process.

1. freezed

e84b05cf89c9d205d88f1ca9548c3354.jpeg

Introduction

Freezed is a Dart-based Flutter library that helps you quickly generate immutable data classes and union types. In Flutter development, we often need to define data classes and union types to represent our data and state. Using Freezed, we can easily define these classes and types and they are all immutable, which helps to improve the performance and maintainability of the application.

scenes to be used

Freezed can be used in the following scenarios:

  • Define immutable data classes and union types.

  • Simplify data class definitions in the state manager.

  • Improve code readability and maintainability.

example

To use the Freezed library, you need to add dependencies to your project. You can add the following code to your pubspec.yaml file:

dependencies:
  freezed: ^1.2.0

Next, you need to create a Dart file that contains the data classes and union types you want to define. In this file, you need to import the frozen_annotation package and define classes with @freezed and @JsonSerializable annotations.

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';

part 'my_class.freezed.dart';
part 'my_class.g.dart';

@freezed
abstract class MyClass with _$MyClass {
  const factory MyClass({
    @required String name,
    @required int age,
  }) = _MyClass;

  factory MyClass.fromJson(Map<String, dynamic> json) =>
      _$MyClassFromJson(json);
}

In the above code, we defined a data class called MyClass. It has two required attributes: name and age. We also define a private class called _MyClass, which is the implementation class of the MyClass class, and is used to generate immutable classes.

To generate implementation classes and JSON serialization and deserialization code, run the following commands:

flutter pub run build_runner build --delete-conflicting-outputs

This will generate a file named my_class.freezed.dart containing the generated code.

Now, we can use the MyClass class in our application, for example:

final myClass = MyClass(name: 'John', age: 30);

https://pub.dev/packages/freezed

2. flutter_native_splash

a32cddb9da55b46e3125b65cc41bf1e5.gif

Introduction

flutter_native_splash is a Flutter library that helps you add a native splash screen when launching your app. By using flutter_native_splash, you can easily create splash screens for Android and iOS platforms without manually editing native code.

scenes to be used

flutter_native_splash is suitable for the following scenarios:

  • Want to add a native splash screen to your application.

  • You don't want to manually edit native code.

example

To use the flutter_native_splash library, you need to add a dependency to your project. You can add the following code to your pubspec.yaml file:

dependencies:
  flutter_native_splash: ^1.2.0

Next, you need to create a splash screen image for your application. You can place this image in the root directory of your application and name it splash.png. You can then add the following code to your pubspec.yaml file to specify your application's splash screen image:

flutter_native_splash:
  image: splash.png

Next, you need to add the following code to your main.dart file to enable the flutter_native_splash library:

import 'package:flutter_native_splash/flutter_native_splash.dart';

void main() {
  // Set the initial route when starting the app
  var initialRoute = '/';

  // Run the app
  runApp(MyApp(initialRoute: initialRoute));

  // Show splash screen before loading the app
  FlutterNativeSplash.show(
    seconds: 5,
    // Put any other FlutterNativeSplash configurations here...
  );
}

In the code above, we first define an initial route and then start our application. Next, we call the FlutterNativeSplash.show() method, which will show the native splash screen and delay the app loading for a certain amount of time (in this case, 5 seconds).

Now, when you launch the app, a native splash screen is displayed.

https://pub.dev/packages/flutter_native_splash

3. go_router

59e2ddea384e3a86f8dc1d728b008909.jpeg

Introduction

go_router is a Flutter library that helps you easily manage routing in your application. By using go_router, you can easily create applications with multiple routes and manage navigation between those routes. go_router also supports multiple navigation stacks, and functions such as routing parameters and callbacks.

scenes to be used

go_router is suitable for the following scenarios:

  • Want to manage an application with multiple routes.

  • Want to manage navigation between routes.

  • It is necessary to support functions such as routing parameters and callbacks.

example

To use the go_router library, you need to add a dependency to your project. You can add the following code to your pubspec.yaml file:

dependencies:
  go_router: ^2.2.0

The following is a complete sample code, which includes an example of creating a GoRouter instance and defining two routes.

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      routerDelegate: GoRouter(
        // Define your routes here
        routes: [
          GoRoute(
            path: '/',
            pageBuilder: (context, state) => HomePage(),
          ),
          GoRoute(
            path: '/detail',
            pageBuilder: (context, state) {
              final args = state.extra['args'] as Map<String, dynamic>;
              return DetailPage(
                title: args['title'],
                subtitle: args['subtitle'],
              );
            },
          ),
        ],
      ),
      routeInformationParser: GoRouterInformationParser(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home')),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            GoRouter.of(context).go('/detail', {
              'title': 'Detail Page',
              'subtitle': 'This is the detail page.',
            });
          },
          child: Text('Go to Detail Page'),
        ),
      ),
    );
  }
}

class DetailPage extends StatelessWidget {
  final String title;
  final String subtitle;

  const DetailPage({
    Key key,
    @required this.title,
    @required this.subtitle,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: Center(
        child: Text(subtitle),
      ),
    );
  }
}

go_router is a great Flutter library that helps you easily manage routing in your application. By using go_router, you can easily create applications with multiple routes and manage navigation between those routes. If you are developing a Flutter application with multiple routes, go_router will be your indispensable helper.

https://pub.dev/packages/go_router

4. just_audio

Introduction

just_audio is a Flutter plugin that provides audio playback functionality for Flutter applications. It uses the platform's native player and provides advanced features such as custom notifications, custom player UI, and audio streaming.

scenes to be used

just_audio is for when you need to play audio in your Flutter app. Whether you want to play music, podcasts, voice memos, or other types of audio, just_audio has you covered.

Since just_audio is implemented based on the platform's native player, it can provide better performance and better user experience.

example

The following is a simple example of using just_audio to play a local audio file. First, the just_audio dependency needs to be added to the pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  just_audio: ^0.9.19

Then, we need to use the AudioPlayer class in our Flutter app to play audio. Here is a simple example of using the AudioPlayer class to play a local audio file:

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

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

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

class AudioPlayerScreen extends StatefulWidget {
  @override
  _AudioPlayerScreenState createState() => _AudioPlayerScreenState();
}

class _AudioPlayerScreenState extends State<AudioPlayerScreen> {
  AudioPlayer _player;

  @override
  void initState() {
    super.initState();
    _player = AudioPlayer();
    _player.setAsset('assets/audio/sample.mp3');
    _player.play();
  }

  @override
  void dispose() {
    _player.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Just Audio Demo')),
      body: Center(
        child: Text('Playing audio...'),
      ),
    );
  }
}

The above code first creates an AudioPlayer instance in the initState method, and uses the setAsset method to load a local audio file. Then, use the play method to start playing the audio.

In the dispose method, the dispose method needs to be called to release the resources occupied by the AudioPlayer instance.

Finally, in the build method, use the Scaffold and Text widgets to show that the audio is playing.

just_audio is a powerful Flutter library that helps you easily play audio in your Flutter applications. With just_audio, you can easily play local and remote audio files, and you can add custom notifications and customize the player UI. If you are developing a Flutter application that requires audio playback, just_audio will be your best choice.

https://pub.dev/packages/just_audio

5. json_serializable

b58f0bb73d0904c8a58600d020afb684.jpeg

Introduction

json_serializable is a Flutter library that automatically generates code related to JSON serialization and deserialization, using the Dart code generator and annotations. This library can help Flutter developers generate related code more efficiently and conveniently when processing JSON data.

scenes to be used:

json_serializable is a very useful tool when you need to serialize/deserialize JSON data in Dart. It can automatically generate the necessary Dart classes, class members, parsing functions and other codes, reducing the workload of manually writing these codes and improving the readability and maintainability of the code.

example

Import library: Add dependencies to the pubspec.yaml file:

dependencies:
  json_annotation: <latest_version>
  json_serializable: <latest_version>

Create a Dart class: Create a Dart class and add a comment above it stating that the class needs to be serialized/deserialized.

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart'; // 这是代码生成器生成的文件

@JsonSerializable() // 告诉 json_serializable 这个类是需要序列化/反序列化的
class User {
  final int id;
  final String name;

  User({
    required this.id,
    required this.name,
  });

  // 自动生成反序列化函数
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  // 自动生成序列化函数
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

Generate relevant code: Run the following command in the terminal to automatically generate relevant code:

flutter pub run build_runner build

Use auto-generated code: Use auto-generated serialization/deserialization code to convert Dart objects to JSON format, or convert JSON format to Dart objects.

import 'dart:convert';

void main() {
  // 将 Dart 对象转换成 JSON 格式
  final user = User(id: 1, name: 'John');
  final jsonString = jsonEncode(user.toJson());
  print(jsonString); // 输出:{"id":1,"name":"John"}

  // 将 JSON 格式转换成 Dart 对象
  final jsonMap = jsonDecode(jsonString);
  final newUser = User.fromJson(jsonMap);
  print(newUser.name); // 输出:John
}

json_serializable is a very useful Flutter library that can help Flutter developers process JSON data more easily. Through annotations and code generators, it can automatically generate serialization/deserialization related codes, reducing the workload of handwritten codes.

https://pub.dev/packages/json_serializable

6. flex_color_scheme

4ecbd35d1537ca17bee3b740208e6261.jpeg

Introduction

flex_color_scheme is a Flutter library for creating flexible, highly customizable color schemes. Use this library to quickly create the color theme of the application, which is convenient for developers to customize according to the design requirements. It also supports the theme specifications of Flutter Material Design and Cupertino (iOS style).

scenes to be used

flex_color_scheme is mainly suitable for those Flutter projects that need to customize the color scheme of the application. Its main usage scenarios include:

  • Quickly create flexible, highly customizable color schemes to suit design requirements.

  • Supports theme specifications for Flutter Material Design and Cupertino (iOS style).

  • Can be easily integrated with Material components in Flutter applications.

  • Applications can be given custom accent colors and brightness.

example

Here are the basic steps to create a custom color scheme using flex_color_scheme:

1. Introduce the flex_color_scheme library into the project.

dependencies:
  flex_color_scheme: ^2.1.1

2. Use FlexColorScheme in Flutter applications to create custom color themes.

import 'package:flex_color_scheme/flex_color_scheme.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'FlexColorScheme Demo',
      theme: FlexColorScheme.light(scheme: FlexScheme.mandyRed),
      darkTheme: FlexColorScheme.dark(scheme: FlexScheme.mandyRed).toTheme,
      home: MyHomePage(),
    );
  }
}

In the example above, we created light and dark color themes using FlexColorScheme.light() and FlexColorScheme.dark(), which accept a scheme parameter that specifies the color scheme.

3. Use FlexColorScheme.themed() in the Flutter component to apply the color theme created above.

Container(
  color: FlexColorScheme.themed(Colors.blue),
  child: Center(
    child: Text('Hello, world!', style: TextStyle(fontSize: 24)),
  ),
),

In the example above, we use FlexColorScheme.themed() to automatically select a background color based on the current color scheme.

https://pub.dev/packages/flex_color_scheme

7. android_intent_plus

737b319fcac9a8344907f54fd25872be.jpeg

Introduction

android_intent_plus is a Flutter plugin that allows you to launch Intents on Android devices, and allows you to specify data and/or actions. Also, it allows you to start an activity with startActivityForResult and receive the result when it completes.

scenes to be used

android_intent_plus is mainly suitable for Flutter applications that need to interact with the Android platform. android_intent_plus may be especially useful in the following scenarios:

Calling APIs of the Android platform: In Flutter, some Android SDK APIs are not directly packaged as Flutter plug-ins. In this case, you can use android_intent_plus to start an Intent to call these APIs.

Launch another application: You can use android_intent_plus to launch other applications and pass data to them. For example, you can use android_intent_plus to launch a browser application and open a specific URL.

Receiving activity results: In some cases, you may need to get results from launched activities. With android_intent_plus, you start an activity using the startActivityForResult method and receive the result when it completes.

example

Using android_intent_plus is very simple. Just add dependencies in the pubspec.yaml file, then import the library in your code, and you're ready to go.

1. Add dependencies

In the pubspec.yaml file, add the following lines to the dependencies section:

dependencies:
  android_intent_plus: ^3.0.0

2. Import library

In any file in your Flutter app, you can import android_intent_plus:

import 'package:android_intent_plus/android_intent.dart';

3. Getting started code example

Here's a simple example of how to use android_intent_plus to launch a browser application and open a specific URL:

import 'package:android_intent_plus/android_intent.dart';

void openBrowser(String url) {
  final intent = AndroidIntent(
    action: 'android.intent.action.VIEW',
    data: Uri.encodeFull(url),
    package: 'com.android.chrome',
    componentName: ComponentName(
      'com.android.chrome',
      'com.google.android.apps.chrome.Main',
    ),
  );
  intent.launch();
}

This code will open the Chrome browser with a specific URL.

android_intent_plus is a very useful Flutter plugin that lets you launch Intents on Android devices and allows you to specify data and/or actions. Also, it allows you to start an activity with startActivityForResult and receive the result when it completes. If you need to interact with the Android platform, android_intent_plus is an option worth considering.

https://pub.dev/packages/android_intent_plus

Summarize

Today, Flutter has become one of the most popular cross-platform development frameworks in the field of mobile application development. In order to improve development efficiency and code quality, using third-party libraries is a common practice in the development process. This article introduces several third-party libraries that are very useful in Flutter development. They are Freezed, flutter_native_splash, GoRouter, just_audio, json_serializable, some libraries in flex_color_scheme and plus_plugins, and android_intent_plus.

These libraries cover different functions and usage scenarios. For example, Freezed can help developers be more efficient in creating and managing data models; flutter_native_splash can provide a custom splash screen for Flutter applications; GoRouter can make application navigation more flexible; just_audio provides a powerful audio playback function for Flutter applications; json_serializable can automatically generate serialization and deserialization codes for Dart data models; flex_color_scheme can help developers create custom color themes for Flutter applications; some libraries in plus_plugins and android_intent_plus can add Android platform specific functionality to the application.

Using these libraries can help Flutter developers improve efficiency during the development process while ensuring high-quality applications and a good user experience. Whether developing a new project or updating an existing one, these libraries are worth checking out.

That’s all for today’s sharing, I hope it will be helpful to you, thank you for reading, it’s not easy to create articles, if you like my sharing, don’t forget to like and forward it, so that more people can see it, and finally don’t forget to pay attention」 Front-end expert", your support will be the biggest motivation for me to share, and I will continue to output more content in the future, so stay tuned.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/129253065