Skip to content

Instantly share code, notes, and snippets.

@SongFuZhen
Last active October 26, 2020 09:54
Show Gist options
  • Save SongFuZhen/ee4a80d6b1c151dc394d20a315d4d2cf to your computer and use it in GitHub Desktop.
Save SongFuZhen/ee4a80d6b1c151dc394d20a315d4d2cf to your computer and use it in GitHub Desktop.

添加背景图片

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

Flutter Create 初始化

flutter create --org com.sfz tab_now

点击两次返回键,退出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;
  
  ...
}

TextField 键盘遮挡处理

在界面布局中使用SingleChildScrollView

Scaffold(
    body: SingleChildScrollView(...)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment