如何截取当前小部件的屏幕截图? : 颤动

时间:2021-05-06 07:54:14

标签: android flutter dart flutter-dependencies dart-pub

我正在尝试截取当前小部件的屏幕截图并希望将其存储在图库中, 我在整个网络上都没有得到该问题的理想答案..

这些是我目前使用的软件包。

flip_card: ^0.5.0
screenshot:

我有我的报价小部件,它被包裹在 flip_card Package 小部件中,

    @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: DefaultAssetBundle.of(context).loadString("jsons/quotes.json"),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (!snapshot.hasData) {
            return Container(
              child: Center(
                child: SizedBox(
                  child: CircularProgressIndicator(),
                  height: 60.0,
                  width: 60.0,
                ),
              ),
            ); // I understand it will be empty for now
          } else {
            var myquotes = json.decode(snapshot.data.toString());
            int lengthofJSON = 1643;
            var rangeofQuotes = random(0, lengthofJSON);

        //var randomMyQuotes = myquotes[0].shuffle().first;
        return FlipCard(
          direction: FlipDirection.HORIZONTAL,
          front: Screenshot(
            controller: screenshotquotes,
            child: Card(
              // color: Colors.transparent,
              child: GradientCard(
                gradient: Gradients.buildGradient(
                    Alignment.topRight, Alignment.bottomLeft, [
                  Colors.blueAccent[700],
                  Colors.blue,
                  Colors.blueAccent[100],
                  // Colors.black54,
                  //  Colors.black87,
                  //  Colors.black87,
                ]),
                semanticContainer: false,
                child: Wrap(
                  children: [
                    Center(
                      child: Column(
                        children: [
                          Padding(
                              padding: EdgeInsets.all(
                                  MediaQuery.of(context).size.width / 20)),
                          Container(
                              child: Icon(CarbonIcons.quotes,
                                  color: Colors.white)),
                          Container(
                              padding: EdgeInsets.all(
                                  MediaQuery.of(context).size.width / 30),
                              child: Text(
                                  "${myquotes[rangeofQuotes]["text"]}",
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: (myquotes[rangeofQuotes]
                                                      ["text"]) //161
                                                  .length >
                                              90
                                          ? 12
                                          : 16))),
                          Container(
                              padding: EdgeInsets.all(
                                  MediaQuery.of(context).size.width / 30),
                              child: Text(
                                  "@${myquotes[rangeofQuotes]["author"]}",
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 12,
                                      fontStyle: FontStyle.italic)))
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),

在背面,我得到了一个背面:(小部件)来自 flip_card 小部件, 看起来像这样,

back: Card(
            // color: Colors.transparent,
            child: GradientCard(
              gradient: Gradients.buildGradient(
                  Alignment.bottomRight, Alignment.topRight, [
                Colors.blueAccent[700],
                Colors.blue,
                Colors.blue[400],
                //Colors.blueAccent[700],
                // Colors.white,
              ]),
              semanticContainer: false,
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                        padding: EdgeInsets.all(
                            MediaQuery.of(context).size.width / 30),
                        child: Text("Share or Download",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ))),
                    Row(
                      children: [
                        Expanded(
                          child: Align(
                            alignment: Alignment.center,
                            child: Center(
                                child: CircleAvatar(
                              radius: 30,
                              backgroundColor: Colors.white,
                              child: IconButton(
                                onPressed: () {},
                                icon: Icon(CarbonIcons.share),
                              ),
                            )),
                          ),
                        ),
                        Expanded(
                          child: Align(
                            alignment: Alignment.center,
                            child: Center(
                                child: CircleAvatar(
                              radius: 30,
                              backgroundColor: Colors.white,
                              child: IconButton(
                                onPressed: () {
                                  screenshotquotes
                                      .capture()
                                      .then((Uint8List image) async {
                                    //Capture Done

                                    setState(() {
                                      _imageFile = image;
                                    });
                                  }).catchError((onError) {
                                    print(onError);
                                  });

                                  print("Quote Captured");
                                  ScaffoldMessenger.of(context)
                                      .showSnackBar(SnackBar(
                                          backgroundColor: Colors.blue[200],
                                          content: Row(
                                            children: [
                                              Expanded(
                                                  flex: 1,
                                                  child: Text("?",
                                                      style: TextStyle(
                                                          color: Colors
                                                              .white))),
                                              Expanded(
                                                  flex: 5,
                                                  child: Text(
                                                    "Quotes, is captured sucessfully",
                                                  )),
                                              // FlatButton(
                                              //   child: Text("Undo"),
                                              //   color: Colors.white,
                                              //   onPressed: () async{
                                              //     await box.deleteAt(index);
                                              //     Navigator.pop(context);
                                              //   },
                                              // ),
                                            ],
                                          )));
                                },
                                icon: Icon(CarbonIcons.download),
                              ),
                            )),
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ),
          ),
        );
      }
    });
  }

  random(min, max) {
    var rn = new Random();
    return min + rn.nextInt(max - min);
  }
}

从所有这些来看,我既没有在我的应用程序的内部文件夹 com.example.tooodo 中获得截图图像,也没有在图库中获得任何东西。

我想在这方面引起您的注意。 谢谢,愿你长高。

1 个答案:

答案 0 :(得分:0)

您可以使用 RepaintBoundary 类,例如将您的 Widget 包装在 RepaintBoundary 类中,如下所示: return Scaffold( appbar:AppBar(), body:Container( child: RepaintBoundary( key : _repaintKey, child:Stack()) ));

不要忘记像 RepaintBoundary 这样提供密钥

 GlobalKey _repaintKey = new GlobalKey();

现在您可以在 RepaintBoundary 中捕获该部分

Future<Uint8List> captureBoundary() async {
try {
  RenderRepaintBoundary boundary =
      _repaintKey.currentContext.findRenderObject();
  Image savedImage = await boundary.toImage(pixelRatio: 3.0);
  ByteData byteData =
      await savedImage.toByteData(format: ImageByteFormat.png);
  UInt8List pngBytes = byteData.buffer.asUint8List();
  saveFile(widget.pickedImage.uri.path, pngBytes);
  return pngBytes;
} catch (e) {
  print(e);
}

}

这里调用 saveFile() 将捕获的图像保存到手机存储中,并在 saveFile 内部

Future<bool> saveFile( var byteList) async {
Directory storageDir;
try {
  if (await requestPermission(Permission.storage)) {
    storageDir = await getExternalStorageDirectory();

    String newPath = '';
    List<String> folders = storageDir.path.split('/');
    for (int x = 1; x < folders.length; x++) {
      String folder = folders[x];
      if (folder != 'Android') {
        newPath += '/' + folder;
      } else {
        break;
      }
    }
    newPath = newPath + '/yourFolderName';
    storageDir = Directory(newPath);
  } else {
    if (await requestPermission(Permission.photos)) {
      storageDir = await getTemporaryDirectory();
    } else {
      return false;
    }
  }
  if (!await storageDir.exists()) {
    await storageDir.create(recursive: true);
  }
  if (await storageDir.exists()) {
    File savedFile = File(storageDir.path + "/yourfileName");
    String savedPath = storageDir.path + "/yourfileName";
    savedFile.writeAsBytesSync(byteList); //the byteList that you send from captureBoundary
    if (savedPath != null) {
      print("File saved");
    } else {
      print("Error saving");
    }
    return true;
  }
} catch (e) {
  print(e);
}
return false;

}

希望,这会有所帮助!