Lập trình Flutter

Hướng dẫn tích hợp AI vào ứng dụng Flutter với Gemini Code Assist và Firebase AI Logic

26/09/2026 Đặng Trí Thanh 185 lượt xem ~7 phút đọc
Mục lục bài viết
    Hướng dẫn tích hợp AI vào ứng dụng Flutter với Gemini Code Assist và Firebase AI Logic

    Tích hợp AI vào ứng dụng Flutter: Hướng dẫn sử dụng Gemini Code Assist và Firebase AI Logic

    Giới thiệu

    Trong thời đại AI phát triển mạnh mẽ, việc tích hợp AI vào ứng dụng di động đang trở thành xu hướng tất yếu. Bài viết này sẽ hướng dẫn bạn cách tích hợp Google Gemini và Firebase AI Logic vào ứng dụng Flutter một cách hiệu quả.

    1. Cài đặt và Cấu hình

    1.1. Thêm dependencies

    # pubspec.yaml
    dependencies:
      flutter:
        sdk: flutter
      google_generative_ai: ^0.2.0
      firebase_core: ^2.24.2
      firebase_ml_kit: ^0.16.3
      google_mlkit_text_recognition: ^0.11.0

    1.2. Cấu hình Firebase

    1. Tạo project trên Firebase Console
    2. Tải file google-services.json cho Android
    3. Tải file GoogleService-Info.plist cho iOS

    2. Tích hợp Gemini AI

    2.1. Khởi tạo Gemini Client

    import 'package:google_generative_ai/google_generative_ai.dart';
    
    class GeminiService {
      final GenerativeModel _model;
    
      GeminiService() {
        _model = GenerativeModel(
          model: 'gemini-pro',
          apiKey: 'YOUR_API_KEY',
        );
      }
    
      Future<String> generateResponse(String prompt) async {
        try {
          final content = [Content.text(prompt)];
          final response = await _model.generateContent(content);
          return response.text ?? 'No response generated';
        } catch (e) {
          print('Error generating response: $e');
          return 'Error occurred while generating response';
        }
      }
    }

    2.2. Tạo UI cho Chat Interface

    class ChatScreen extends StatefulWidget {
      @override
      _ChatScreenState createState() => _ChatScreenState();
    }
    
    class _ChatScreenState extends State<ChatScreen> {
      final TextEditingController _controller = TextEditingController();
      final List<ChatMessage> _messages = [];
      final GeminiService _geminiService = GeminiService();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('AI Chat')),
          body: Column(
            children: [
              Expanded(
                child: ListView.builder(
                  itemCount: _messages.length,
                  itemBuilder: (context, index) => _messages[index],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _controller,
                        decoration: InputDecoration(
                          hintText: 'Type your message...',
                          border: OutlineInputBorder(),
                        ),
                      ),
                    ),
                    IconButton(
                      icon: Icon(Icons.send),
                      onPressed: _sendMessage,
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      }
    
      void _sendMessage() async {
        if (_controller.text.isEmpty) return;
    
        final userMessage = ChatMessage(
          text: _controller.text,
          isUser: true,
        );
    
        setState(() {
          _messages.add(userMessage);
          _controller.clear();
        });
    
        final response = await _geminiService.generateResponse(userMessage.text);
    
        setState(() {
          _messages.add(ChatMessage(
            text: response,
            isUser: false,
          ));
        });
      }
    }

    3. Tích hợp Firebase AI Logic

    3.1. Cấu hình Firebase ML Kit

    import 'package:firebase_ml_kit/firebase_ml_kit.dart';
    
    class FirebaseAIService {
      final TextRecognizer _textRecognizer = FirebaseVision.instance.textRecognizer();
    
      Future<String> recognizeText(String imagePath) async {
        try {
          final FirebaseVisionImage image = 
              FirebaseVisionImage.fromFilePath(imagePath);
          final VisionText visionText = 
              await _textRecognizer.processImage(image);
    
          return visionText.text;
        } catch (e) {
          print('Error recognizing text: $e');
          return 'Error occurred while recognizing text';
        }
      }
    }

    3.2. Tạo UI cho Text Recognition

    class TextRecognitionScreen extends StatefulWidget {
      @override
      _TextRecognitionScreenState createState() => _TextRecognitionScreenState();
    }
    
    class _TextRecognitionScreenState extends State<TextRecognitionScreen> {
      final FirebaseAIService _aiService = FirebaseAIService();
      String _recognizedText = '';
      bool _isProcessing = false;
    
      Future<void> _processImage() async {
        setState(() {
          _isProcessing = true;
        });
    
        // Implement image picking logic here
        final String imagePath = await ImagePicker().getImage();
    
        if (imagePath != null) {
          final text = await _aiService.recognizeText(imagePath);
          setState(() {
            _recognizedText = text;
            _isProcessing = false;
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Text Recognition')),
          body: Column(
            children: [
              if (_isProcessing)
                CircularProgressIndicator()
              else
                Expanded(
                  child: SingleChildScrollView(
                    padding: EdgeInsets.all(16),
                    child: Text(_recognizedText),
                  ),
                ),
              ElevatedButton(
                onPressed: _processImage,
                child: Text('Select Image'),
              ),
            ],
          ),
        );
      }
    }

    4. Best Practices và Tips

    4.1. Xử lý lỗi và Retry Logic

    class AIService {
      Future<T> withRetry<T>(Future<T> Function() operation) async {
        int maxAttempts = 3;
        int attempt = 0;
    
        while (attempt < maxAttempts) {
          try {
            return await operation();
          } catch (e) {
            attempt++;
            if (attempt == maxAttempts) rethrow;
            await Future.delayed(Duration(seconds: attempt * 2));
          }
        }
        throw Exception('Max retry attempts reached');
      }
    }

    4.2. Caching Responses

    class AICache {
      final Map<String, String> _cache = {};
    
      String? getCachedResponse(String prompt) {
        return _cache[prompt];
      }
    
      void cacheResponse(String prompt, String response) {
        _cache[prompt] = response;
      }
    }

    5. Performance Optimization

    5.1. Lazy Loading và Pagination

    class PaginatedChat extends StatefulWidget {
      @override
      _PaginatedChatState createState() => _PaginatedChatState();
    }
    
    class _PaginatedChatState extends State<PaginatedChat> {
      final ScrollController _scrollController = ScrollController();
      final List<ChatMessage> _messages = [];
      bool _isLoading = false;
      int _page = 1;
    
      @override
      void initState() {
        super.initState();
        _scrollController.addListener(_scrollListener);
        _loadMessages();
      }
    
      void _scrollListener() {
        if (_scrollController.position.pixels ==
            _scrollController.position.maxScrollExtent) {
          _loadMoreMessages();
        }
      }
    
      Future<void> _loadMoreMessages() async {
        if (_isLoading) return;
    
        setState(() {
          _isLoading = true;
        });
    
        // Implement pagination logic here
        final newMessages = await _loadMessagesFromAPI(_page++);
    
        setState(() {
          _messages.addAll(newMessages);
          _isLoading = false;
        });
      }
    }

    6. Testing

    6.1. Unit Tests

    void main() {
      group('GeminiService Tests', () {
        late GeminiService service;
    
        setUp(() {
          service = GeminiService();
        });
    
        test('generateResponse returns valid response', () async {
          final response = await service.generateResponse('Hello');
          expect(response, isNotEmpty);
        });
      });
    }

    6.2. Widget Tests

    void main() {
      testWidgets('Chat UI Test', (WidgetTester tester) async {
        await tester.pumpWidget(MaterialApp(home: ChatScreen()));
    
        expect(find.text('AI Chat'), findsOneWidget);
        expect(find.byType(TextField), findsOneWidget);
        expect(find.byIcon(Icons.send), findsOneWidget);
      });
    }

    Kết luận

    Việc tích hợp AI vào ứng dụng Flutter không chỉ giúp tăng tính năng thông minh cho ứng dụng mà còn mở ra nhiều cơ hội phát triển mới. Với Gemini và Firebase AI Logic, bạn có thể dễ dàng thêm các tính năng AI vào ứng dụng của mình.

    Tài liệu tham khảo

    1. Google Gemini Documentation
    2. Firebase ML Kit Documentation
    3. Flutter AI Integration Guide

    Liên hệ

    Nếu bạn có thắc mắc hoặc cần hỗ trợ thêm, hãy liên hệ:

    .hndl-embed-wrap{max-width:800px;margin:28px auto 24px}
    .hndl-embed-wrap iframe{display:block;width:100% !important;max-width:100% !important;border:0;background:#fff;height:470px}
    @media (max-width:640px){.hndl-embed-wrap iframe{height:520px}}

    Đặng Trí Thanh

    Đặng Trí Thanh

    Giám đốc Công nghệ · DNT Digital · Giảng viên HNDL Hướng Nghiệp Dữ Liệu

    1.393
    Bài viết
    15.4k
    Người theo dõi
    120k+
    Lượt đọc

    Đặng Trí Thanh — Founder & CTO · Hướng Nghiệp Dữ Liệu – DNT Digital. Chuyên đào tạo và triển khai thực chiến Python, MT5 và hệ thống bot auto trading / IB cho học viên và doanh nghiệp.

    document.addEventListener(‘DOMContentLoaded’, function() {
    const btn = document.getElementById(‘hndl-btn-follow’);
    const countSpan = document.getElementById(‘hndl-follower-count’);
    if (!btn || !countSpan) return;

    const authorId = ‘1’;
    const storageKey = ‘hndl_followed_author_’ + authorId;

    // Kiểm tra trạng thái đã follow từ LocalStorage
    let isFollowed = localStorage.getItem(storageKey) === ‘true’;

    function updateUI() {
    if (isFollowed) {
    btn.textContent = ‘Đang theo dõi’;
    btn.classList.add(‘active’);
    countSpan.textContent = ‘15.5k’;
    } else {
    btn.textContent = ‘Theo dõi’;
    btn.classList.remove(‘active’);
    countSpan.textContent = ‘15.4k’;
    }
    }

    updateUI();

    btn.addEventListener(‘click’, function() {
    isFollowed = !isFollowed;
    localStorage.setItem(storageKey, isFollowed ? ‘true’ : ‘false’);

    // Hiệu ứng micro-animation
    btn.style.transform = ‘scale(0.95)’;
    setTimeout(() => {
    btn.style.transform = ‘none’;
    updateUI();
    }, 100);
    });
    });

    Bài viết liên quan về Flutter

    Tham khảo thêm khóa học lập trình Flutter đa nền tảng của Hướng Nghiệp Dữ Liệu.

    .hndl-embed-wrap{max-width:800px;margin:28px auto 24px}
    .hndl-embed-wrap iframe{display:block;width:100% !important;max-width:100% !important;border:0;background:#fff;height:470px}
    @media (max-width:640px){.hndl-embed-wrap iframe{height:520px}}

    Đặng Trí Thanh

    Đặng Trí Thanh

    Giám đốc Công nghệ · DNT Digital · Giảng viên HNDL Hướng Nghiệp Dữ Liệu

    1.400
    Bài viết
    15.4k
    Người theo dõi
    120k+
    Lượt đọc

    Đặng Trí Thanh — Founder & CTO · Hướng Nghiệp Dữ Liệu – DNT Digital. Chuyên đào tạo và triển khai thực chiến Python, MT5 và hệ thống bot auto trading / IB cho học viên và doanh nghiệp.

    document.addEventListener(‘DOMContentLoaded’, function() {
    const btn = document.getElementById(‘hndl-btn-follow’);
    const countSpan = document.getElementById(‘hndl-follower-count’);
    if (!btn || !countSpan) return;

    const authorId = ‘1’;
    const storageKey = ‘hndl_followed_author_’ + authorId;

    // Kiểm tra trạng thái đã follow từ LocalStorage
    let isFollowed = localStorage.getItem(storageKey) === ‘true’;

    function updateUI() {
    if (isFollowed) {
    btn.textContent = ‘Đang theo dõi’;
    btn.classList.add(‘active’);
    countSpan.textContent = ‘15.5k’;
    } else {
    btn.textContent = ‘Theo dõi’;
    btn.classList.remove(‘active’);
    countSpan.textContent = ‘15.4k’;
    }
    }

    updateUI();

    btn.addEventListener(‘click’, function() {
    isFollowed = !isFollowed;
    localStorage.setItem(storageKey, isFollowed ? ‘true’ : ‘false’);

    // Hiệu ứng micro-animation
    btn.style.transform = ‘scale(0.95)’;
    setTimeout(() => {
    btn.style.transform = ‘none’;
    updateUI();
    }, 100);
    });
    });

    .hndl-embed-wrap{max-width:800px;margin:28px auto 24px}
    .hndl-embed-wrap iframe{display:block;width:100% !important;max-width:100% !important;border:0;background:#fff;height:470px}
    @media (max-width:640px){.hndl-embed-wrap iframe{height:520px}}

    Đặng Trí Thanh

    Đặng Trí Thanh

    Giám đốc Công nghệ · DNT Digital · Giảng viên HNDL Hướng Nghiệp Dữ Liệu

    1.397
    Bài viết
    15.4k
    Người theo dõi
    120k+
    Lượt đọc

    Đặng Trí Thanh — Founder & CTO · Hướng Nghiệp Dữ Liệu – DNT Digital. Chuyên đào tạo và triển khai thực chiến Python, MT5 và hệ thống bot auto trading / IB cho học viên và doanh nghiệp.

    document.addEventListener(‘DOMContentLoaded’, function() {
    const btn = document.getElementById(‘hndl-btn-follow’);
    const countSpan = document.getElementById(‘hndl-follower-count’);
    if (!btn || !countSpan) return;

    const authorId = ‘1’;
    const storageKey = ‘hndl_followed_author_’ + authorId;

    // Kiểm tra trạng thái đã follow từ LocalStorage
    let isFollowed = localStorage.getItem(storageKey) === ‘true’;

    function updateUI() {
    if (isFollowed) {
    btn.textContent = ‘Đang theo dõi’;
    btn.classList.add(‘active’);
    countSpan.textContent = ‘15.5k’;
    } else {
    btn.textContent = ‘Theo dõi’;
    btn.classList.remove(‘active’);
    countSpan.textContent = ‘15.4k’;
    }
    }

    updateUI();

    btn.addEventListener(‘click’, function() {
    isFollowed = !isFollowed;
    localStorage.setItem(storageKey, isFollowed ? ‘true’ : ‘false’);

    // Hiệu ứng micro-animation
    btn.style.transform = ‘scale(0.95)’;
    setTimeout(() => {
    btn.style.transform = ‘none’;
    updateUI();
    }, 100);
    });
    });

    Đặng Trí Thanh

    Đặng Trí Thanh

    Giám đốc Công nghệ · DNT Digital · Giảng viên HNDL Hướng Nghiệp Dữ Liệu
    1.398 Bài viết
    15.4k Người theo dõi
    120k+ Lượt đọc

    Đặng Trí Thanh — Founder & CTO · Hướng Nghiệp Dữ Liệu - DNT Digital. Chuyên đào tạo và triển khai thực chiến Python, MT5 và hệ thống bot auto trading / IB cho học viên và doanh nghiệp.

    Thẻ: (chưa gắn thẻ)

    Bài viết liên quan

    DNT DIGITAL

    🤖 AI CODE: Vibe Code NEEDED! 🚀 🏦 SSI • DNSE • MT5 • Bitget ⚡

    Zalo 0934145100
    Khóa đào tạo
    Hỗ trợ

    Được học lại miễn phí · Hỗ trợ trọn đời · Cập nhật miễn phí

    Đội ngũ hỗ trợ

    Đặng Trí Thanh
    Đặng Trí Thanh
    Giám đốc Công nghệ DNT Digital
    Zalo 0934145100
    Mộng Cầm
    Mộng Cầm
    Hỗ trợ khách hàng · Huấn luyện viên
    Zalo 0927909257
    Khánh Linh
    Khánh Linh
    Hỗ trợ khách hàng · Huấn luyện viên
    Zalo 0927909582