[Flutter] Hướng dẫn tạo plugin và gọi thư viện native

Giới thiệu

Hiện nay tài liệu cho việc tạo plugin cho flutter khá ít, mà tài liệu để plugin gọi xuống các thư viện native càng hiếm hơn nữa. Nên hôm nay mình viết bài này để giúp mọi người dễ dàng hơn trong việc viết plugin với flutter. Cùng bắt đầu thôi nào!

Phần 1. Hướng dẫn tạo plugin

Để tạo 1 plugin bạn cần dùng lệnh flutter create –template=plugin

  • Sử dụng tùy chọn –platforms để chỉ định plugin sẽ có những ngôn ngữ nào. Có các tùy chọn như: android, ios, web, linux, macos, windows
  • Sử dụng tùy chọn –org để chỉ định tên miền cho tổ chức của bạn
  • Sử dụng tùy chọn –a để chỉ định ngôn ngữ cho android. Bạn có thể chọn java hoặc kotlin
  • Sử dụng tùy chọn –i để chỉ định ngôn ngữ cho ios. Bạn có thể chọn swift hoặc objc
  • Và cuối cùng sẽ là tên plugin của bạn

Tham khảo:

flutter create --org com.example --template=plugin --platforms=android,ios -a kotlin -i swift sample_plugin_flutter

Sau khi thao tác trên bạn sẽ có 1 plugin trong thư mục sample_plugin_flutter với một số file cơ bản sau:

  • lib/sample_plugin_flutter.dart => API Dart cho plugin. File này dùng để kết nối các thành phần của plugin, kết nối với native code
  • android/src/main/kotlin/com/example/sample_plugin_flutter/SamplePluginFlutterPlugin.kt => Triển khai API plugin trong Kotlin dành riêng cho nền tảng Android.
  • ios/Classes/SwiftSamplePluginFlutterPlugin.swift => Triển khai API plugin trong Swift dành riêng cho nền tảng iOS.
  • example/ => Một ứng dụng Flutter phụ thuộc vào plugin và minh họa cách sử dụng nó.
  • lib/src/ => Thư mục này sẽ không có sẵn, nhưng bạn cần tạo thư mục này để chứa các file private. Bạn chỉ public các file cần thiết thông qua khai báo export trong lib/sample_plugin_flutter.dart

Phần 2. Hướng dẫn tạo Widget với plugin

Để tạo Widget hay Function để người dùng plugin để thể gọi và sử dụng, bạn cần đưa file đó vào thư mục src và export nó ra ngoài. Khi làm vậy, người dùng chỉ cần import 1 dòng duy nhất là có thể sử dụng plugin của bạn.

Trong thư mục lib/src các bạn tạo 1 file dart mới và đặt tên là sample_button.dart

import 'package:flutter/material.dart';

class SampleButton extends StatelessWidget {
  final String text;
  final VoidCallback? onPressed;

  const SampleButton({
    Key? key,
    required this.text,
    this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: onPressed,
      child: Container(
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.blue,
          borderRadius: BorderRadius.circular(10),
        ),
        child: Text(
          text,
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}

Trong thư mục lib/src các bạn tạo thêm file src.dart, file này sẽ chứa tất cả file mà bạn muốn export ra ngoài.

export 'sample_button.dart';

Trong file lib/sample_plugin_flutter.dart bạn nên xóa hết code mặc định đi. File này các bạn sẽ chứa những file bạn muốn export hoặc export những plugin khác có trong dependence của bạn.

export 'src/src.dart';

Giờ thì thử build Widget này lên từ app example nhé. Trong file example/lib/main.dart bạn đổi lại code như sau:

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              /// Phần 2. Hướng dẫn tạo Widget với plugin
              SampleButton(
                text: "Sample Button",
                onPressed: () {
                  print("Sample Button Click");
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Chạy flutter run để xem kết quả thôi nào.

Sample 1

Còn tiếp

Bài viết đầy đủ tại Viblo

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.