Flutter for Android Developers 官方文档笔记

官方文档

官方文档笔记

Views

Flutter 中与 View 相等的东西是什么?

Widget 具有 Android 中 View 的作用。

区别:

  1. 生命周期不同:Widget 是不可变的,每次界面变化就会创建新的 WidgetWidgetState 变化也会形成新的 Widget 对象
  2. 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 中实现界面之间跳转:

  1. Specify a Map of route names. (MaterialApp)
  2. 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 添加点击事件?

有两种方式添加触摸事件:

  1. Widget 的 onPressed 参数
@override
Widget build(BuildContext context){
    return RaisedButton(
        onPressed: (){
            print("click");
        },
        child: Text("Button")
    );
}
  1. 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 通常有两种:

  1. MaterialApp
  2. 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

Notifications

消息推送?

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 春雨飘落时 我走在青石板的小路上 风轻柔中夹着微凉 湖边柳树的身姿在荡漾 二月的天空明净爽朗 繁花编成彩色的海洋 ...
    说剑师阅读 148评论 0 3
  • 入夜渐微凉,慢慢冷下来的日子,感受到了自己的努力 ,可是越认真越在乎结果 越害怕结果 过程就越艰辛!害怕自己努力却...
    可乐sty阅读 196评论 0 0
  • 由于input和button都是行内块级元素所以有间隙。浮动后变为块级元素间隙消失。也可以flexbox布局更方便...
    没人能救你呀吼阅读 993评论 0 0