flutter备忘录

一篇很好的文章https://www.jianshu.com/p/a0d67d368b92

Container背景图片(设置圆角)

Container(
                    height: 60,
                    width: 300,
                    decoration: BoxDecoration(
                      color: Colors.red,
                      image: DecorationImage(image: AssetImage("images/worldBuilding/zhifubao.png"),fit: BoxFit.fitHeight),
                      borderRadius: BorderRadius.all(Radius.circular(60))
                    ),
                  )

圆角按钮

Container(
              height: 45,
              width: MediaQuery.of(context).size.width,
              margin: const EdgeInsets.only(left: 20,right: 20,bottom: 20),
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border.all(color: Colors.blue,width: 1),
                  borderRadius: BorderRadius.all(Radius.circular(20))),
              child: Container(
                child: FlatButton(
                    onPressed: () {
                      _onPressLogin();
                    },
                    shape: RoundedRectangleBorder(
                        borderRadius:
                        BorderRadius.all(Radius.circular(20))),
                    child: Text(
                      "手机登录/注册",
                      style: TextStyle(color: Colors.blue, fontSize: 14),
                    )),
              ),
            )

屏幕宽高

MediaQuery.of(context).size.width;
MediaQuery.of(context).size.height;

Container的width、height

width:container的宽度,设置为double.infinity可以强制在宽度上撑满,不设置,则根据child和父节点两者一起布局。

height:container的高度,设置为double.infinity可以强制在高度上撑满。

Android状态栏去掉背景

//MainActivity中代码
public class MainActivity extends FlutterActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //修改状态栏颜色
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
      getWindow().setStatusBarColor(0);
    }
    GeneratedPluginRegistrant.registerWith(this);
  }
}

设置状态栏文字颜色

//在ThemeData中设置
appBarTheme: AppBarTheme(
            color: Colors.white,
            brightness: Brightness.dark,//状态栏亮色调,文字黑色
            iconTheme: IconThemeData(
                color: Colors.black54,
                opacity: 1,
              size: 100,
            )
        )

在当前页面设置状态栏文字颜色

//方法一:在Android可以,在iOS好像不可以
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light
            .copyWith(statusBarBrightness: Brightness.light));
//方法二
return AnnotatedRegion(
      value: SystemUiOverlayStyle.dark,
      child: Material(child:Scaffold(
        body: Container(color: Colors.white,),
      ),),);

参考文章
https://www.jianshu.com/p/15700d9145aa
https://blog.csdn.net/wo122282967/article/details/88788851
https://www.jianshu.com/p/9409845d8794

内容显示到状态栏位置

@override
  Widget build(BuildContext context) {
    
    return Scaffold(
      body: ListView.builder(
        padding: const EdgeInsets.all(0.0),//设置padding属性
          itemBuilder: _itemBuilder
      ),
    );
}

支付宝蚂蚁森林滚动渐变导航栏效果以及页面显示到最上面

  @override
  Widget build(BuildContext context) {
    
    // TODO: implement build
    return Scaffold(
      body: Stack(
        children: [
          ListView.builder(
            padding: const EdgeInsets.all(0.0), //内容显示到最上面,状态栏背后
            controller: _scrollController,
            itemBuilder: _itemBuilder,
            itemCount: itemCount,
          ),
          Positioned()//这里手写导航栏
        ],
      ),
    );
  }
_scrollController.addListener((){
      print("偏移量${_scrollController.offset}");
      if (_scrollController.offset < 20) {
        SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light
            .copyWith(statusBarBrightness: Brightness.light));
        setState(() {
          this._actionBarView = null;
        });
      }
      //and so on
    });

圆角头像带点击事件

FlatButton(onPressed: (){
                    _showImgPicker();
                  }, child: Container(
                    height: 70,
                    width: 70,
                    child: ClipOval(
                      child: _image == null
                          ? Image.asset("images/mine/touxiangzhanwei.png")
                          : Image.file(_image,fit: BoxFit.fitWidth,),
                    ),
                  ))

pub finished with exit code 78

如果运行此行出错

flutter packages pub run build_runner build

那么可以直接运行

flutter packages pub run build_runner build --delete-conflicting-outputs

图片上传

Dio支持发送 FormData, 请求数据将会以 multipart/form-data方式编码, FormData中可以一个或多个包含文件 .

注意: 只有 post 方法支持发送 FormData.

FormData formData = new FormData.from({
    "name": "wendux",
    "age": 25,
    "file": new UploadFileInfo(new File("./example/upload.txt"), "upload.txt")
});
response = await dio.post("/info", data: formData)

图片转二进制流

File imgFile;

imgFile.readAsBytes().then((data) {
    
    });

flutter打包

首先务必详细阅读官方说明文档,根据flutter官网进行配置
Androidhttps://flutterchina.club/android-release/
iOShttps://flutterchina.club/ios-release/

iOS进入工程目录下运行

flutter build ios

成功之后重新打开xcode打包

Android进入工程目录下运行

flutter build apk

成功之后获取包 /build/app/outputs/apk/app-release.apk

flutter实现微信登录/微信分享

在微信开放平台设置签名,那么怎么获取签名呢?

  1. 进入key.jks文件所在目录
    2.运行命令 keytool -list -v -keystore key.jks
    3.获取MD5值,去掉中间分号输入到微信开放平台中

⚠️我只是试了一下这么做可以,不知道其他方式可不可以

flutter截图

声明key切图使用

GlobalKey rootWidgetKey = GlobalKey(); 
/*获取截图*/
  Future _capturePng() async {
    try {
      RenderRepaintBoundary boundary =
          rootWidgetKey.currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 2.5);//控制图片清晰度
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      return pngBytes; //这个对象就是图片数据
    } catch (e) {
      print(e);
    }
//    return null;
  }
//截图区域
RepaintBoundary(
                      key: rootWidgetKey,
                       child: Container(),//要截取的区域
)

flutter图片文件读写

_capturePng().then((imgData) {
      if (imgData != null) {
        getApplicationDocumentsDirectory().then((appDocDir) {
          String appDocPath = appDocDir.path + "/shareImg.png";
          File file = File(appDocPath);
          file.writeAsBytes(imgData).then((f) {
            if (type == 1) {
              fluwx
                  .share(WeChatShareImageModel(
                      image: "file://" + appDocPath,
                      scene: WeChatScene.SESSION))
                  .then((a) {
                print("微信分享结果" + a.toString());
              });
            } else if (type == 2) {
              fluwx
                  .share(WeChatShareImageModel(
                      image: "file://" + appDocPath,
                      scene: WeChatScene.TIMELINE))
                  .then((a) {
                print("微信分享结果" + a.toString());
              });
            }
          });
        });
      }
    });

适配刘海屏SafeArea

如果整个页面只使用SafeArea

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return SafeArea(
      child: Container(
        color: Colors.red,
      ),
    );
  }

可以看到页面显示避开了上下的安全区域

flutter备忘录_第1张图片
safeArea-01.png

我们可以手动关闭其适应上下安全区

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return SafeArea(
      child: Container(
        color: Colors.red,
      ),
      top: false,
      bottom: false,
    );
  }
flutter备忘录_第2张图片
safeArea-02.png

当页面使用Scaffold时不需要考虑顶部安全区域了,只适配底部就可以了

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.yellow, //可以用来设置底部安全区域的背景颜色(当bottom: true时)
      appBar: AppBar(
        title: Text("SafeArea"),
      ),
      body: SafeArea(
        child: Container(
          color: Colors.red,
        ),
        bottom: true, //true不将内容显示到底部安全区域內,false将内容显示到底部安全区域
      ),
    );
  }
flutter备忘录_第3张图片
safeArea-03.png
flutter备忘录_第4张图片
safeArea-04.png

flutter长按复制

                                    GestureDetector(
                                      onLongPress: (){
                                        Clipboard.setData(ClipboardData(text: "[email protected]"));
                                        Fluttertoast.showToast(msg: "邮箱已复制到剪切板");
                                      },
                                      child: Text("[email protected]",
                                          style: TextStyle(
                                              fontSize: 16,
                                              color: Colors.black)),
                                    )

软键盘顶起布局

Scaffold(
  resizeToAvoidBottomPadding: false,
)

double保留后2位小数

double vv = 12.3333333;
vv.toStringAsFixed(2);

跳转页面顺便关掉当前页面

Navigator.pushReplacement( context, MaterialPageRoute(builder: (BuildContext context) => MainPage()));

你可能感兴趣的:(flutter备忘录)