官方文檔筆記
Views
Flutter 中與 View 相等的東西是什麼?
Widget
具有 Android 中 View 的作用。
區別:
- 生命週期不同:
Widget
是不可變的,每次界面變化就會創建新的Widget
,Widget
的State
變化也會形成新的Widget
對象 -
Widget
是輕量級的。它不是 View 不會自己繪製內容,只是用於描述界面的。
如何更新 Widgets?
需要通過改變 Widget
的 state 達到更新界面的效果。
Widget 根據是否有狀態可以分爲:
- StatelessWidgets: 無狀態的 Widget
- StatefulWidget: 有狀態的 Widget
StatefulWidget 父 Widget 可以是 StatelessWidget
Widget 如何佈局?
Flutter 中在 widget tree 中寫佈局
如何添加和移除一個 Widget 從界面中?
Android 中通常使用 addChild
,removeChild
實現動態添加和移除控件。
在 Flutter 中做法:
_getToggleChild() {
if (toggle) {
return Text('Toggle One');
} else {
return MaterialButton(onPressed: () {}, child: Text('Toggle Two'));
}
}
body: Center(
child: _getToggleChild(),
)
通過改變 toggle 達到移除和添加 Widget 的效果。
Widget 如何添加動畫?
在 Flutter 中需要使用 動畫庫中的Widgets 包裹 普通Widgets
body: Center(
child: Container(
child: FadeTransition(
opacity: curve,
child: FlutterLogo(
size: 100.0,
)))),
如何使用 Cancas 繪製
使用 CustomPainter
如何自定義 Widgets
Flutter 中自定義 Widgets, 通常是其他 小Widget 的組合。
class CustomButton extends StatelessWidget {
final String label;
CustomButton(this.label);
@override
Widget build(BuildContext context) {
return RaisedButton(onPressed: () {}, child: Text(label));
}
}
Flutter 中類似 Intents 的東西?
Android 中通過 Intents 實現界面直接的跳轉和傳值。
Flutter 中通過 Navigator
, Route
實現界面跳轉。
在 Android 中需要在 AndroidManifest.xml
中聲明 Activity.
在 Flutter 中實現界面之間跳轉:
- Specify a Map of route names. (MaterialApp)
- Directly navigate to a route. (WidgetApp)
build map 例子:
void main() {
runApp(MaterialApp(
home: MyAppHome(), // becomes the route named '/'
routes: <String, WidgetBuilder> {
'/a': (BuildContext context) => MyPage(title: 'page A'),
'/b': (BuildContext context) => MyPage(title: 'page B'),
'/c': (BuildContext context) => MyPage(title: 'page C'),
},
));
}
Navigate to a route by push its name to the Navigator.
Navigator.of(context).pushNamed('/b');
如何獲取外部傳入的 intents?
Flutter 通過和 Android 層交互實現獲取 外部intents
startActivityForResult() 在 Flutter 中的類似?
await
, push
Map coordinates = await Navigator.of(context).pushNamed('/location');
pop
的時候返回值
Navigator.of(context).pop({"lat":43.821757,"long":-79.226392});
Aysnc UI
runOnUiThread 在 Flutter 中?
Dart has a single-threaded execution model, with support for Isolates (a way to run Dart code on another thread), an event loop, and asynchronous programming.
Dart 有一種單線程執行的模式,支持 Isolate(用於在其他線程執行代碼),一個事件隊列,和異步的程序設計。
除非使用 Isolate, Dart 的代碼都在 主線程 中運行,並且被一個 事件隊列 驅動。
Flutter 中的事件隊列類是 Android Main Looper。
異步實現:
loadData() async {
String dataURL = "https://jsonplaceholder.typicode.com/posts";
http.Response response = await http.get(dataURL);
setState(() {
widgets = json.decode(response.body);
});
}
如何實現後臺任務?
Android: AsyncTask
, LiveData
, IntentService
, JobScheduler
, RxJava
In Flutter, use Isolates
to take advantage of multiple CPU cores to do long-running or computationally intensive tasks.
Isolates are separate execution threads that do not share any memory with the main execution memory heap.
Isloates 中不能使用 setState()
去修改 UI.
OKHttp 在 Flutter 中的替代品?
http
包
如何顯示長任務的進度條?
ProgressIndicator
Project structure & resources
圖片資源存放在哪裏?
Android density qualifier Flutter pixel ratio
ldpi 0.75x
mdpi 1.0x
hdpi 1.5x
xhdpi 2.0x
xxhdpi 3.0x
xxxhdpi 4.0x
文件夾:
images/my_icon.png
images/2.0x/my_icon.png
images/3.0x/my_icon.png
在 pubspec.yaml
中聲明:
assets:
- images/my_icon.png
使用:
@override
Widget build(BuildContext context){
return Image.asset("images/my_icon.png")
}
如何存儲 string, 多語言如何處理?
class Strings{
static String welcomeMessage = "Welcome to flutter";
}
Text(Strings.welcomeMessage)
目前爲止只能通過靜態類存儲重複使用的字符串。
包管理工具?
pubspec.yaml
Activites and fragments
What are the equivalent of activities and fragments in Flutter?
在 Flutter 中 Activity 和 Fragment 的作用都被 Widget 替代。
如何監聽 activity 生命週期?
通過 WidgetsBinding
和 監聽 didChangeAppLifecycleState()
獲取生命週期:
inactive: IOS 獨有,表示應用處在不可用狀態。
paused:應用在後臺。
resumed:應用到前臺,可見
suspending: Android 獨有,應用暫停,類似 Android onStop
Layouts 佈局
LinearLayout 替代品?
@override
Widget build(BuildContext context){
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Row Oen'),
Text('Row Two'),
Text('Row Three'),
Text('Row Four'),
],
);
}
使用 Row
, Column
代替 LinearLayout
RelativeLayout 替代品?
無
ScrollView 替代品?
Flutter 中的 ListView
可以替代 Android 中的 ScrollView
, ListView
橫屏模式如何處理?
FlutterView handles the config change if AndroidManifest.xml contains:
android:configChanges="orientation|screenSize"
Gesture detection and touch event handling 手勢檢測和觸摸事件處理
如何給 Widget 添加點擊事件?
有兩種方式添加觸摸事件:
- Widget 的
onPressed
參數
@override
Widget build(BuildContext context){
return RaisedButton(
onPressed: (){
print("click");
},
child: Text("Button")
);
}
- widget 不支持觸摸事件監測的時候,使用
GestureDetector
包裹控件
@override
Widget build(BuildContext context){
return Scaffold(
body: Center(
child: GestureDetector(
size: 200.0
),
onTap: (){
print("tap");
},
),
);
}
如何捕獲其他事件?
Tap:
- onTapDown
- onTapUp
- onTap
- onTapCancel
Double Tap:
- onDoubleTap
Long press:
- onLongPress
Vertical drag:
- onVerticalDragStart
- onVerticalDragUpdate
- onVerticalDragEnd
Horizontal drag:
- onHorizontalDragStart
- onHorizontalDragUpdate
- onHorizontalDragEnd
ListViews & adapters
ListView 的替代品在?
在 Flutter 中使用 ListView 替代 Android 中的 ListView.
Flutter 中不需要 adapter,只需要創建 List<Widget> 傳入到 ListView 中即可,也不需要控件的回收管理。
如何知道點擊的 item
widget 是獨立的,所有點擊事件也是獨立的:
_getListData() {
List<Widget> widgets = [];
for (int i = 0; i < 100; i++) {
widgets.add(GestureDetector(
child: Padding(
padding: EdgeInsets.all(10.0),
child: Text("Row $i")),
onTap: () {
print('row tapped');
},
));
}
return widgets;
}
如何動態更新 ListView?
直接修改 List widgets = []
數據源,重建對象。
在數據量大的時候推薦使用 ListView.Builder
, 這個類似 RecyclerView,會自動回收複用 list 的 item。在修改數據的時候不能重建對象,而是給 widgets
添加或者刪除數據。
Working with text
如何自定義字體
把 字體文件 放到文件夾中,然後在 pubspec.yaml
中申明:
fonts:
- family: MyCustomFont
fonts:
- asset: fonts/MyCustomFont.ttf
- style: italic
使用:
@override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text("Sample App")
),
body: Center(
child: Text(
'This is a custom font text',
style: TextStyle(fontFamily: 'MyCustomFont'),
),
),
);
}
Text widgets 樣式
- color
- decoration
- decorationColor
- decorationStyle
- fontFamily
- fontSize
- fontStyle
- fontWeight
- hashCode
- height
- inherit
- letterSpacing
- textBaseline
- wordSpacing
Form input
hint 設置
body: Center(
child: TextField(
decoration: InputDecoration(hintText: "This is a hint"),
)
)
如何顯示驗證錯誤信息?
decoration: InputDecoration(hintText: "This is a hint"), errorText: _getErrorText()
_getErrirText() {
return _errorText;
}
Flutter plugins
-
geolocator
: GPS 傳感器使用插件 -
image_picker
: 相機操作 -
flutter_facebook_login
: 使用 Facebook 登入插件
Firebase 相關:。。。
自定義插件
如何使用 NDK
Themes
主題定義?
Flutter 中定義 themes 在 top level widget。
top level widget 通常有兩種:
- MaterialApp
- WidgetApp
通過參數 ThemeData 修改主題的顏色。
class SampleApp extends StatelessWidget{
@override
Widget build(BuildContext context){
return MaterialApp(
title: 'Sample App',
theme: ThemeData(
primarySwatch: Colors.blue,
textSelectionColor: Colors.red
),
home: SampleAppPage(),
);
}
}
Databases and local storage
Shared Preferences 如何使用?
通過插件使用 Shared_Preferences
同時支持 Android, IOS
SQLite
Android: SQFlite