Flutter 的一些知识点

E.F.S.F. 销声匿迹 沉默是金 本文由博客端 https://blog.eiyouhe.com 主动推送

flutter

1.intro

flutter 本质是 widget 树

2.layout

自适应: 根据设备发生变化。

响应式: 根据屏幕大小发生变化。

自适应应用

视觉密度

widget 的疏密程度,紧凑程度等意思,其实就是一个动态的值来自动调整宽高/间距什么的

基于 Context 的布局

以下是反转屏幕的一个判断,可以基于媒体查询判断是否反转,从顶传入子,使得整个 UI 做出屏幕翻转的响应

bool isHandset = MediaQuery.of(context).size.width < 600;
return Flex(
  children: [...],
  direction: isHandset ?
    Axis.vertical :
    Axis.horizontal
);

layout builder

layout builder 和之前不同的是,提供了一些对象,让你更好的做出判断和使用

Widget foo = LayoutBuilder(builder: (_, constraints, __){
 bool useVerticalLayout = constraints.maxWidth < 400.0;
 return Flex(
     children: [...],
     direction: useVerticalLayout ?
     Axis.vertical : Axis.horizontal
 );
});

设备细分

// Platform对象判断设备类型
bool get isMobileDevice => !kIsWeb && (Platform.isIOS || Platform.isAndroid);
// macos windows
bool get isDesktopDevice =>
    !kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux);
// browser
bool get isMobileDeviceOrWeb => kIsWeb || isMobileDevice;
bool get isDesktopDeviceOrWeb => kIsWeb || isDesktopDevice;

input

鼠标

MouseRegion
return MouseRegion(
// 进入
  onEnter: (_) => setState(() => _isMouseOver = true),
// 离开
onExit: (_) => setState(() => _isMouseOver = false),
// 悬停
onHover: (PointerHoverEvent e) => print(e.localPosition),
  child: ...,
);

用户期望

布局约束

首先,上层 widget 向下层 widget 传递约束条件。

然后,下层 widget 向上层 widget 传递大小信息。

最后,上层 widget 决定下层 widget 的位置。

长宽计算更像是 子向父报备,父汇集各个子然后计算,在向父父汇报

限制 外到内,外告知内可小于外宽松约束,外告知内必须变成某个大小严格约束

添加互动

指定资源

flutter:
  assets:
    - assets/my_icon.png
    - assets/background.png


flutter:
  assets:
    - directory/
    - directory/subdirectory/

// 直接读文件了
Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/config.json');
}

// 不同分辨率的图片,可FLutter可以对应不同的设备自动切换
.../my_icon.png
.../2.0x/my_icon.png
.../3.0x/my_icon.png

// 使用别的包的图像,也要声明出来
flutter:
  assets:
    - packages/fancy_backgrounds/backgrounds/background1.png

注意: 读取 android/ios 图片插件和方式不同,文件夹内有 android,ios 两个文件夹,需要添加各自的插件,图标,预加载图 也是如此

路由

安卓启动深度路由 AndroidManifest.xml

<!-- Deep linking -->
<meta-data android:name="flutter_deeplinking_enabled" android:value="true" />
<intent-filter android:autoVerify="true">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="http" android:host="flutterbooksample.com" />
    <data android:scheme="https" />
</intent-filter>

配合 adb 测试

adb shell am start -a android.intent.action.VIEW \
    -c android.intent.category.BROWSABLE \
    -d "http://flutterbooksample.com/book/1"

IOS Info.plist

<key>FlutterDeepLinkingEnabled</key>
<true/>
<key>CFBundleURLTypes</key>
<array>
    <dict>
    <key>CFBundleTypeRole</key>
    <string>Editor</string>
    <key>CFBundleURLName</key>
    <string>flutterbooksample.com</string>
    <key>CFBundleURLSchemes</key>
    <array>
    <string>customscheme</string>
    </array>
    </dict>
</array>

配合 xsrun xshell

xcrun simctl openurl booted customscheme://flutterbooksample.com/book/1

动画

pass

http

import 'package:http/http.dart' as http;

var url = Uri.parse('https://example.com/whatsit/create');
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');

print(await http.read('https://example.com/foobar.txt'));

安卓需要在 AndroidManifest.xml 中添加需要访问的网络权限

<manifest xmlns:android...>
 ...
 <uses-permission android:name="android.permission.INTERNET" />
 <application ...
</manifest>

json

class User {
  final String name;
  final String email;

  User(this.name, this.email);
// 解析json
  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        email = json['email'];
// 转成json
  Map<String, dynamic> toJson() => {
        'name': name,
        'email': email,
      };
}

或者

dependencies:
  # Your other regular dependencies here
  json_annotation: <latest_version>

dev_dependencies:
  # Your other dev_dependencies here
  build_runner: <latest_version>
  json_serializable: <latest_version>

引入依赖,使用注解

@JsonSerializable()
class User {
  User(this.name, this.email);

  String name;
  String email;

  /// A necessary factory constructor for creating a new User instance
  /// from a map. Pass the map to the generated `_$UserFromJson()` constructor.
  /// The constructor is named after the source class, in this case, User.
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  /// `toJson` is the convention for a class to declare support for serialization
  /// to JSON. The implementation simply calls the private, generated
  /// helper method `_$UserToJson`.
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

i18n

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations: # Add this line
    sdk: flutter         # Add this line



return const MaterialApp(
  title: 'Localizations Sample App',
  localizationsDelegates: [
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: [
    Locale('en', ''), // English, no country code
    Locale('es', ''), // Spanish, no country code
  ],
  home: MyHomePage(),
);

添加自定义国际化文件

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: ^0.17.0 # Add this line



# The following section is specific to Flutter.
flutter:
  generate: true # Add this line

然后添加 arb 配置

arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart

arb 文件

{
    "helloWorld": "Hello World!",
    "@helloWorld": {
      "description": "The conventional newborn programmer greeting"
    }
}

导入本地配置

localizationsDelegates: [
    AppLocalizations.delegate, // Add this line
 ``   ],

代码中使用

Text(AppLocalizations.of(context)!.helloWorld);
  • Flutter

    Flutter 是谷歌的移动 UI 框架,可以快速在 iOS 和 Android 上构建高质量的原生用户界面。 Flutter 可以与现有的代码一起工作,它正在被越来越多的开发者和组织使用,并且 Flutter 是完全免费、开源的。

    39 引用 • 92 回帖 • 4 关注

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • jann

    学习了。