Mobile Dev
Flutter 4.0: Xây Dựng App Đa Nền Tảng Với Một Code Base
Khám phá Flutter 4.0 - framework Google cho phép build iOS, Android, Web, Desktop từ một mã nguồn duy nhất
10 phút đọc
NhiTuyen Tech Blog Team
Flutter 4.0: Một Code Base, Mọi Platform
Flutter 4.0 đánh dấu bước tiến lớn trong phát triển ứng dụng đa nền tảng. Với Impeller rendering engine mới và WebAssembly support, Flutter giờ đây nhanh hơn và mạnh mẽ hơn bao giờ hết!
Flutter 4.0 Có Gì Mới?
1. Impeller Rendering Engine
Engine render mới thay thế Skia với hiệu suất vượt trội:
- 🚀 60-120 FPS ổn định
- ⚡ Giảm jank và stuttering
- 🎨 Shader compilation cải thiện
- 📱 Pin tốt hơn 15-20%
// Impeller tự động enabled trên iOS/Android
// Không cần config gì thêm! 🎯
void main() {
runApp(MyApp());
}
2. WebAssembly Support
Flutter Web giờ compile sang WASM thay vì JavaScript:
- 📦 Bundle size giảm 40%
- ⚡ Load time nhanh hơn 2-3x
- 🎯 Performance gần native
# Build Flutter Web với WASM
flutter build web --wasm
# Output: Blazing fast web app! 🔥
Tại Sao Chọn Flutter?
Write Once, Run Everywhere
// Code này chạy trên:
// ✅ iOS
// ✅ Android
// ✅ Web
// ✅ Windows
// ✅ macOS
// ✅ Linux
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
useMaterial3: true, // Material Design 3! 🎨
),
home: HomePage(),
);
}
}
Hot Reload - Developer Experience Tuyệt Vời
// Thay đổi UI, see results < 1 second! ⚡
class CounterApp extends StatefulWidget {
@override
State<CounterApp> createState() => _CounterAppState();
}
class _CounterAppState extends State<CounterApp> {
int _counter = 0;
void _increment() {
setState(() {
_counter++; // Change và hot reload instantly!
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Counter')),
body: Center(
child: Text(
'$_counter',
style: Theme.of(context).textTheme.displayLarge,
),
),
floatingActionButton: FloatingActionButton(
onPressed: _increment,
child: Icon(Icons.add),
),
);
}
}
Material Design 3 & Adaptive Widgets
Beautiful UI Out of the Box
// Material Design 3 components
class ModernUI extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Material You'),
// Dynamic color từ wallpaper! 🎨
),
body: ListView(
children: [
// Filled button - Primary action
FilledButton(
onPressed: () {},
child: Text('Get Started'),
),
// Card với elevation mới
Card(
elevation: 0,
child: ListTile(
leading: Icon(Icons.notifications),
title: Text('New message'),
subtitle: Text('You have 3 unread messages'),
),
),
// Navigation bar hiện đại
NavigationBar(
destinations: [
NavigationDestination(
icon: Icon(Icons.home),
label: 'Home',
),
NavigationDestination(
icon: Icon(Icons.search),
label: 'Search',
),
],
),
],
),
);
}
}
Adaptive Widgets
// Tự động adapt theo platform!
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class AdaptiveButton extends StatelessWidget {
final VoidCallback onPressed;
final String text;
@override
Widget build(BuildContext context) {
// iOS: Cupertino style
// Android: Material style
return PlatformWidget(
cupertino: CupertinoButton(
onPressed: onPressed,
child: Text(text),
),
material: ElevatedButton(
onPressed: onPressed,
child: Text(text),
),
);
}
}
State Management
Riverpod - Modern State Management
import 'package:flutter_riverpod/flutter_riverpod.dart';
// Define provider
final counterProvider = StateProvider<int>((ref) => 0);
// Use trong widget
class CounterPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
// Watch counter changes
final counter = ref.watch(counterProvider);
return Scaffold(
body: Center(
child: Text('Count: $counter'),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Update state
ref.read(counterProvider.notifier).state++;
},
child: Icon(Icons.add),
),
);
}
}
// Type-safe, compile-time checked! ✅
BLoC Pattern
import 'package:flutter_bloc/flutter_bloc.dart';
// Events
abstract class CounterEvent {}
class Increment extends CounterEvent {}
class Decrement extends CounterEvent {}
// State
class CounterState {
final int count;
CounterState(this.count);
}
// BLoC
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(CounterState(0)) {
on<Increment>((event, emit) {
emit(CounterState(state.count + 1));
});
on<Decrement>((event, emit) {
emit(CounterState(state.count - 1));
});
}
}
// Predictable state management! 🎯
Animations & Gestures
Implicit Animations
class AnimatedDemo extends StatefulWidget {
@override
State<AnimatedDemo> createState() => _AnimatedDemoState();
}
class _AnimatedDemoState extends State<AnimatedDemo> {
bool _isExpanded = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
_isExpanded = !_isExpanded;
});
},
child: AnimatedContainer(
duration: Duration(milliseconds: 300),
curve: Curves.easeInOut,
width: _isExpanded ? 200 : 100,
height: _isExpanded ? 200 : 100,
color: _isExpanded ? Colors.blue : Colors.red,
child: Center(
child: Text('Tap me!'),
),
),
);
}
}
// Smooth 60fps animations! ⚡
Hero Animations
// Page 1
Hero(
tag: 'profile-pic',
child: CircleAvatar(
backgroundImage: NetworkImage(user.avatarUrl),
radius: 30,
),
)
// Page 2 - Auto animated transition!
Hero(
tag: 'profile-pic',
child: Image.network(
user.avatarUrl,
width: 200,
height: 200,
),
)
Native Integration
Platform Channels
// Gọi native code từ Flutter
import 'package:flutter/services.dart';
class NativeBridge {
static const platform = MethodChannel('com.app/battery');
Future<int> getBatteryLevel() async {
try {
final int result = await platform.invokeMethod('getBatteryLevel');
return result;
} catch (e) {
return -1;
}
}
}
// Swift (iOS)
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(...) -> Bool {
let controller = window?.rootViewController as! FlutterViewController
let batteryChannel = FlutterMethodChannel(
name: "com.app/battery",
binaryMessenger: controller.binaryMessenger
)
batteryChannel.setMethodCallHandler { (call, result) in
if call.method == "getBatteryLevel" {
self.receiveBatteryLevel(result: result)
}
}
return super.application(...)
}
}
FFI - Dart Foreign Function Interface
// Call C/C++ libraries trực tiếp!
import 'dart:ffi';
import 'package:ffi/ffi.dart';
typedef NativeAdd = Int32 Function(Int32 a, Int32 b);
typedef DartAdd = int Function(int a, int b);
void main() {
final dylib = DynamicLibrary.open('libnative.so');
final add = dylib
.lookup<NativeFunction<NativeAdd>>('native_add')
.asFunction<DartAdd>();
print(add(10, 20)); // 30
// Performance native-level! 🚀
}
Testing
Widget Tests
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Counter increments', (WidgetTester tester) async {
// Build widget
await tester.pumpWidget(MyApp());
// Verify initial state
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap button
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify updated state
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
// Fast, reliable testing! ✅
Integration Tests
import 'package:integration_test/integration_test.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('Full app flow', (tester) async {
app.main();
await tester.pumpAndSettle();
// Login flow
await tester.enterText(find.byKey(Key('email')), 'user@test.com');
await tester.enterText(find.byKey(Key('password')), 'password123');
await tester.tap(find.text('Login'));
await tester.pumpAndSettle();
// Verify logged in
expect(find.text('Dashboard'), findsOneWidget);
});
}
Performance Optimization
Build Performance
// ❌ Bad - Rebuilds entire tree
class BadWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: List.generate(1000, (i) =>
ExpensiveWidget(i)
),
);
}
}
// ✅ Good - Use const constructor
class GoodWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: List.generate(1000, (i) =>
const ExpensiveWidget(key: ValueKey(i))
),
);
}
}
ListView.builder for Large Lists
// ✅ Efficient scrolling - chỉ build visible items
ListView.builder(
itemCount: 10000,
itemBuilder: (context, index) {
return ListTile(
title: Text('Item $index'),
subtitle: Text('Details...'),
);
},
)
// Smooth scrolling với 10k items! 🚀
Firebase Integration
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
// Authentication
final auth = FirebaseAuth.instance;
await auth.signInWithEmailAndPassword(
email: 'user@example.com',
password: 'password',
);
// Firestore
final firestore = FirebaseFirestore.instance;
await firestore.collection('posts').add({
'title': 'Flutter 4.0',
'content': 'Amazing!',
'timestamp': FieldValue.serverTimestamp(),
});
// Real-time updates
firestore.collection('posts').snapshots().listen((snapshot) {
for (var doc in snapshot.docs) {
print(doc.data());
}
});
Deployment
iOS
# Build iOS app
flutter build ios --release
# Open in Xcode để upload lên App Store
open ios/Runner.xcworkspace
Android
# Build APK
flutter build apk --release
# Build App Bundle (recommended)
flutter build appbundle --release
# Upload to Google Play Console 🚀
Web
# Build for web
flutter build web --release --wasm
# Deploy to Firebase Hosting
firebase deploy --only hosting
Package Ecosystem
Popular Packages
# pubspec.yaml
dependencies:
flutter:
sdk: flutter
# State Management
flutter_riverpod: ^2.4.0
# Networking
dio: ^5.4.0
# Local Storage
shared_preferences: ^2.2.0
hive: ^2.2.3
# UI Components
flutter_animate: ^4.3.0
shimmer: ^3.0.0
# Utils
intl: ^0.18.0
logger: ^2.0.0
Flutter vs React Native
| Feature | Flutter | React Native |
|---|---|---|
| Language | Dart | JavaScript/TypeScript |
| Performance | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| UI Rendering | Own engine | Native components |
| Hot Reload | ✅ | ✅ |
| Desktop Support | ✅ | ❌ |
| Package Ecosystem | Growing | Mature |
| Learning Curve | Medium | Easy (if know JS) |
Kết Luận
Flutter 4.0 là framework hoàn hảo cho:
- 📱 Mobile apps (iOS & Android)
- 🌐 Progressive Web Apps
- 🖥️ Desktop applications
- 🎯 MVP và prototyping nhanh
- 💰 Dự án có budget hạn chế
// Start your Flutter journey today!
void main() {
print('🚀 Flutter 4.0');
print('⚡ Write once, run everywhere');
print('🎨 Beautiful UI by default');
print('💪 Production-ready');
runApp(YourAwesomeApp());
}
Bạn đã build app với Flutter chưa? Share dự án của bạn! 💬
Tags
#Flutter #Dart #MobileDevelopment #CrossPlatform #iOS #Android #WebDevelopment #GoogleFlutter
Tags:
#Flutter
#Dart
#Mobile Development
#Cross-platform
#iOS
#Android
Bài viết liên quan
Bài viết liên quan 1
Bài viết liên quan 2
Bài viết liên quan 3