Flutter生成二維碼並截圖保存

準備工作:兩個依賴一個插件

生成二維碼插件依賴

保存圖片插件依賴,開始想用path_provider保存圖片來着,代碼運行後可以返回保存圖片的路徑但是保存不到手機中,小編不是專業搞安卓開發的沒深究

截圖插件:RepaintBoundary

開始上代碼:

//首先在你需要生成二維碼頁面中聲明一個GlobalKey
GlobalKey _globalKey = new GlobalKey();

//生成二維碼,並將二維碼包裹在RepaintBoundary插件中
//截圖插件
RepaintBoundary(
  key: _globalKey,
  //生成二維碼插件
  child: QrImage(
    //小編這裏把生成的二維碼設置了前後背景色,不設置的情況下保存圖片後因爲是png格式的,白色透明的地方都是黑色的,導致查看圖片時就是一個黑圖
    foregroundColor: Colors.white,   //前景色
    backgroundColor: Colors.black,   //背景色
    data: "你的二維碼鏈接",
    size: 200.0,
  ),
),

//隨便寫個按鈕什麼的截圖
RaisedButton(
  color: Colors.blue,
  child: Text(
    "保存二維碼",
    style: TextStyle(
      color: Colors.white
    ),
  ),
  onPressed: (){
    //截圖保存圖片方法
    _widgetShot();
  },
)

Future<Uint8List> _widgetShot () async {
    RenderRepaintBoundary boundary = _globalKey.currentContext.findRenderObject();
    var image = await boundary.toImage();
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    final result = await ImageGallerySaver.saveImage(Uint8List.fromList(pngBytes));
    if (result != null && result != "") {
        //返回路徑
        String str = Uri.decodeComponent(result);
        Fluttertoast.showToast(
            msg: "成功保存到$str",
            gravity: ToastGravity.BOTTOM,
            timeInSecForIos: 5
        );
    } else {
        Fluttertoast.showToast(
            msg: "保存失敗",
            gravity: ToastGravity.BOTTOM,
            timeInSecForIos: 3
        );
    }
  }

大功告成!!!其他引用的插件各位在編輯器裏提示引用下就可以了~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章