SongFuZhen
7/30/2019 - 8:40 AM

Flutter 编码相关

Flutter Create 初始化

flutter create --org com.sfz tab_now

添加背景图片

Container(
    decoration: BoxDecoration(
        image: DecorationImage(
            image: AssetImage("assets/background.png"),
            fit: BoxFit.fill)),
    child: ...
);

TextField 键盘遮挡处理

在界面布局中使用SingleChildScrollView

Scaffold(
    body: SingleChildScrollView(...)
)

点击两次返回键,退出App

保证Router中的home已经设置了

解决方案

使用WillPopScope监听返回按键

Widget中使用如下

import 'package:flutter/services.dart'; // 用来退出app
import 'dart:io'; // 用来退出app

...

Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          // 点击返回键的操作
          if (lastPopTime == null ||
              DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
            lastPopTime = DateTime.now();
            Toast.show("再按一次退出", context, duration: Toast.LENGTH_SHORT);

            return false;
          } else {
            // 退出app
            lastPopTime = DateTime.now();
            await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
            exit(0);
            return true;
          }
        },
        child: yourContent )});

在tab页中,多个页面切换时如何保持原页面状态

/// 切换页面的时候,保持状态不刷新
///
///实现原理,使用AutomaticKeepAliveClientMixin,并重写wantKeepAlive方法,让状态不被回收掉

class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin {
  ...
  
  @override
  bool get wantKeepAlive => true;
  
  ...
}