Flutter 5.1 - Responsive & Adaptive
1, Cách tính height, width widget:
- Khai báo 1 biến đựng widget :
Ví dụ:
final appBar = AppBar(
// khai báo appBar để có thể lấy chiều cao của appbar : appBar.preferredSize
title: Text('Personal Expenses'),
actions: [
// btn add ở thanh appbar
IconButton(
onPressed: () {
_startAddNewTransaction(context);
},
icon: Icon(Icons.add),
),
],
);
- Lấy chiều cao bằng cách :
appBar.preferredSize.height
2, Height, witdh màn hình:
MediaQuery.of(context).size.height
MediaQuery.of(context).size.width
Ngoài ra còn tính đc pixel, padding,... bằng cách MediaQuery.of(context).*something*
*Nên tạo biến mediaQuery sử dụng lại để ko phải khởi tạo nhiều lần => hiệu suất kém
Chỉ sử dụng mediaQuery khi thực sự cần thiết, nên tách các widget cần sử dụng đến mediaQuery sang 1 class riêng để tránh rebuild ... (giải thích rõ hơn ở bài sau).
final mediaQuery = MediaQuery.of(context);
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
runApp(MyApp());
}
4, Check lanscape mode:
final isLanscape = MediaQuery.of(context).orientation == Orientation.landscape;
Để UI ko bị vỡ ở chế độ landscape => vẽ lại UI ở chế độ lanscape T.T
if(isLancape){
showUILanscape
}
if(!isLancape){
showUIPortait
}
Note: vẽ UI ở trong hàm Widget build nên chỉ có thể dùng if chứ ko có if else.
5, Di chuyển UI TextField lên trên bàn phím khi bàn phím hiển thị:
return SingleChildScrollView( // tránh view over size sau khi đc nâng lên
child: Card(
elevation: 5,
child: Container(
padding: EdgeInsets.only(
top: 10,
left: 10,
right: 10,
bottom: MediaQuery.of(context).viewInsets.bottom + 10, // cao hơn bàn phím 10
),
6, Hiển thị UI theo platform:
import thư viện này trước khi import thư viện flutter (coding convention import theo thứ tự thư viện dart - flutter - package)
import 'dart:io';
Platform.isIOS ? doIOS : doOtherPlatfor*Android thiết kế theo material design còn iOS theo cupertino style.
Để sử dụng material design :
import 'package:flutter/material.dart';
Cupertino design:
import 'package:flutter/cupertino.dart';
* sử dụng safeArea để tránh UI hiển thi vọt lên tai thỏ trong iOS.
* nên viết common các TextField, Button,.. adaptive theo các platform để dễ dàng sử dụng, ko duplicate code.
Nhận xét
Đăng nhận xét