android

Flutter 开发笔记

2019-09-29  本文已影响0人  calary

一、前言

最近在使用Flutter开发新项目,但是有很多小的使用点很容易遗忘,这里做下笔记,以备下次使用时查阅

二、小笔记汇总

/// 在body上添加一个手势控件,实现键盘回收
@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: (){
          // 键盘回收
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child:Container()
      )
    );
  }

2、进入界面键盘主动弹出

TextField(
    style: TextStyle(fontSize: 20),
    controller: _textController,
    keyboardType: TextInputType.number,
    autofocus: true, // 设置为true则主动弹出
    inputFormatters: [ // 限制输入
    LengthLimitingTextInputFormatter(6),
    WhitelistingTextInputFormatter.digitsOnly
    ],
   decoration: InputDecoration(
       hintText: "键盘主动弹出",
       border: InputBorder.none, // 去掉下滑线
       contentPadding: EdgeInsets.all(0), // 居中
      ),
),        
// 延时1s执行返回
Future.delayed(Duration(seconds: 1), (){
   Navigator.of(context).pop();
});
/// 控件介绍
 const WillPopScope({
    Key key,
    @required this.child, // 可以将界面写到这里
    @required this.onWillPop, // 在这里处理返回事件
  }) : assert(child != null),
       super(key: key);

/// 具体用法
/// .........
@override
  Widget build(BuildContext context) { 
    return WillPopScope(
        child: Scaffold(
          body: Container(
                child: Text('WillPopScope使用介绍')
          ),
        ),
        onWillPop: _requestPop
    );
  }

// 手动处理返回事件
  Future<bool> _requestPop() async{
    Navigator.pop(context);//返回上一个界面
    return Future.value(false); // false 则不退出,true 退出
  }
/// 导入包
import 'package:flutter/services.dart';
/// .........
@override
  Widget build(BuildContext context) { 
    return WillPopScope(
        child: Scaffold(
          body: Container(
                child: Text('退出应用')
          ),
        ),
        onWillPop: _requestPop
    );
  }
/// 返回按钮点击事件
 Future<bool> _requestPop() async{
    SystemNavigator.pop();;//退出应用
    return Future.value(false); 
  }
Text('字体去除下滑线',style: TextStyle( decoration: TextDecoration.none))
// 获取本地语言类型
Locale locale = Localizations.localeOf(context);
String localLanguage =  locale.languageCode; // 语言 en-英文 zh-中文
String localCountry = locale.countryCode; // 地区
1、修改后执行flutter get
2、执行flutter clean
3、重新build安装
flutter clean
flutter build ios --release

Android打包可以直接在项目中打包,配置好密钥等信息后直接执行,注意storeFile路径中不能有中文

// 默认使用系统的key,位置为/User/xxxx/.android/debug.keystore
flutter build apk
import 'dart:io';

void getPlatform(){
  if (Platform.isIOS){

  }else if (Platform.isAndroid){

  }
}
TextField(
      decoration: InputDecoration(
                hintText: "用户名或邮箱",
                border: InputBorder.none, // 去掉下滑线
                contentPadding: EdgeInsets.all(0)
),
ClipRRect (
         borderRadius: BorderRadius.circular(4),
         child: Image.asset("images/header.png"),
    ),
return Scaffold(
  appBar: AppBar(
    elevation: 0.0,
    title: new Text("下面一行代码防止整个界面上移"),
  ),

  resizeToAvoidBottomPadding: false, //输入框抵住键盘
);

1、把Dialog的content单独拿出来,单独用一个Stateful Widget包裹来,
用独立的setState绕过Dialog实现控制内部动态组件的刷新。

2、弹窗控件内部StatefulBuilder 包裹也可以实现更新,
参考:https://blog.csdn.net/qq_39081974/article/details/109097324
Container(
      padding: EdgeInsets.only(top: ScreenUtil().size(10), bottom: ScreenUtil().size(10)),
      child: Text.rich(
        TextSpan(
          style: TextStyle(fontSize: ScreenUtil().font_15, color: ColorsUtil.blueColor),
          children: [
            WidgetSpan(
              child: Image.asset('images/info/icon.png', width: ScreenUtil().size(20), height: ScreenUtil().size(20)),
            ),
            TextSpan(
              text: "你好这样就可以带着图标一块换行了呀",
            ),
          ],
        ),
      ),
    );

三、其他代码无关

Waiting for another flutter command to release the startup lock...

有时候会出现如上等待其他指令执行,但是久久不能好,这个时候关闭IDE也是无效的,具体解决办法可以找到flutter路径,删除路径下的lockfile文件,删除之后再运行,我的文件地址为/Users/xxxxxx/app/flutter/bin/cache/lockfile

2019-09-23 16:50:13.088675+0800 Runner[1474:642130] [VERBOSE-2:dart_vm_data.cc(19)] VM snapshot invalid and could not be inferred from settings.
2019-09-23 16:50:13.089348+0800 Runner[1474:642130] [VERBOSE-2:dart_vm.cc(245)] Could not setup VM data to bootstrap the VM from.
2019-09-23 16:50:13.089495+0800 Runner[1474:642130] [VERBOSE-2:dart_vm_lifecycle.cc(89)] Could not create Dart VM instance.
2019-09-23 16:50:13.090369+0800 Runner[1474:642130] [VERBOSE-3:shell.cc(212)] Check failed: vm. Must be able to initialize the VM.
(lldb)
image.png

如上图所示,选择Release模式运行

chh@chhdeMacBook-Pro ~ % flutter create
No option specified for the output directory.
Create a new Flutter project.

If run on a project that already exists, this will repair the project,
recreating any files that are missing.

Usage: flutter create <output directory>
-h, --help                     Print this usage information.
    --[no-]pub                 Whether to run "flutter pub get" after the
                               project has been created.
                               (defaults to on)

    --[no-]offline             When "flutter pub get" is run by the create
                               command, this indicates whether to run it in
                               offline mode or not. In offline mode, it will
                               need to have all dependencies already available
                               in the pub cache to succeed.

    --[no-]with-driver-test    Also add a flutter_driver dependency and generate
                               a sample 'flutter drive' test.

-t, --template=<type>          Specify the type of project to create.

          [app]                (default) Generate a Flutter application.
          [package]            Generate a shareable Flutter project containing
                               modular Dart code.
          [plugin]             Generate a shareable Flutter project containing
                               an API in Dart code with a platform-specific
                               implementation for Android, for iOS code, or for
                               both.

-s, --sample=<id>              Specifies the Flutter code sample to use as the
                               main.dart for an application. Implies
                               --template=app. The value should be the sample ID
                               of the desired sample from the API documentation
                               website (http://docs.flutter.dev). An example can
                               be found at
                               https://master-api.flutter.dev/flutter/widgets/Si
                               ngleChildScrollView-class.html

    --list-samples=<path>      Specifies a JSON output file for a listing of
                               Flutter code samples that can created with
                               --sample.

    --[no-]overwrite           When performing operations, overwrite existing
                               files.

    --description              The description to use for your new Flutter
                               project. This string ends up in the pubspec.yaml
                               file.
                               (defaults to "A new Flutter project.")

    --org                      The organization responsible for your new Flutter
                               project, in reverse domain name notation. This
                               string is used in Java package names and as
                               prefix in the iOS bundle identifier.
                               (defaults to "com.example")

    --project-name             The project name for this new Flutter project.
                               This must be a valid dart package name.

-i, --ios-language             [objc, swift (default)]
-a, --android-language         [java, kotlin (default)]
    --[no-]androidx            Generate a project using the AndroidX support
                               libraries

Run "flutter help" to see global options.
创建选项

根据图片提示知道执行下面可以指定语言,使用下面的命令就可以创建oc和java项目了
flutter create -i objc -a java flutter_demo

// 错误信息
[ERROR:flutter/shell/gpu/gpu_surface_gl.cc(64)] Failed to setup Skia Gr context.

解决方案:
1、指令运行

// 终端运行下列命令运行
flutter run --enable-software-rendering

2、配置信息

AndroidStudio->Run->Edit Configurations->Additional arguments 
输入 --enable-software-rendering
diff: /Users/XXXX/XXXX/XXXX/XXXX/XXXX/ios/Pods/Manifest.lock: No such file or directory
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.

解决方法

1、 close xcode and enter ios directory
2、rm -rf Runner.xcworkspace
3、pod install

四、外文链接

有很多文章也进行了很棒的总结,这里贴出地址

上一篇 下一篇

猜你喜欢

热点阅读