【问题标题】:Issue with Creating a Screenshot button for my app using Dart (Flutter)使用 Dart (Flutter) 为我的应用程序创建屏幕截图按钮的问题
【发布时间】:2020-03-28 19:19:47
【问题描述】:

我正在尝试捕获小部件的屏幕截图并将其保存到手机图库,但它给了我如下错误。我需要帮助>

W/System.err(23529): java.io.FileNotFoundException: /storage/emulated/0/hsp_app/1575363381281.png(没有这样的文件或 目录)W / System.err(23529):在 java.io.FileOutputStream.open0(Native Method) W/System.err(23529): at java.io.FileOutputStream.open(FileOutputStream.java:287) W / System.err(23529):在 java.io.FileOutputStream.(FileOutputStream.java:223) W / System.err(23529):在 java.io.FileOutputStream.(FileOutputStream.java:171) W / System.err(23529):在 com.example.imagegallerysaver.ImageGallerySaverPlugin.saveImageToGallery(ImageGallerySaverPlugin.kt:61) W / System.err(23529):在 com.example.imagegallerysaver.ImageGallerySaverPlugin.onMethodCall(ImageGallerySaverPlugin.kt:33) W / System.err(23529):在 io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:222) W / System.err(23529):在 io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:96) W / System.err(23529):在 io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:656) W/System.err(23529):在 android.os.MessageQueue.nativePollOnce(Native 方法)W/System.err(23529):在 android.os.MessageQueue.next(MessageQueue.java:325) W/System.err(23529): 在 android.os.Looper.loop(Looper.java:142) W / System.err(23529):在 android.app.ActivityThread.main(ActivityThread.java:6494) W/System.err(23529): 在 java.lang.reflect.Method.invoke(Native 方法)W/System.err(23529):在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) W / System.err(23529):在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

这是我的代码:

import 'package:screenshot/screenshot.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

//...

body: new Container(
child: Screenshot(
              controller: screenshotController,
              // contents...
),),
floatingActionButton: FloatingActionButton.extended(
            onPressed: () {
              _imageFile = null;
              screenshotController
                  .capture()
                  .then((File image) async {
                print("Capture Done");
                setState(() {
                  _imageFile = image;
                });
                final result =
                await ImageGallerySaver.saveImage(image.readAsBytesSync()); // Save image to gallery
                print("File Saved to Gallery");
              }).catchError((onError) {
                print(onError);
              });
            },
            tooltip: 'Capture Result as Screenshot',
            icon: Icon(Icons.save),
            label: Text("Save")
          ),

【问题讨论】:

    标签: flutter dart screenshot


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    你需要权限WRITE_EXTERNAL_STORAGE

    第一步:在AndroidManifest.xml中添加权限。

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    第二步:使用包simple_permissions获取权限
    代码sn-p

    @override
      void initState() {
        super.initState();
        _requestWritePermission();
      }
    
      _requestWritePermission() async {
        PermissionStatus permissionStatus = await SimplePermissions.requestPermission(Permission.WriteExternalStorage);
    
        if (permissionStatus == PermissionStatus.authorized) {
          setState(() {
            _allowWriteFile = true;
          });
        }
      }
    

    工作演示

    完整代码

    import 'dart:io';
    import 'dart:typed_data';
    
    import 'package:flutter/material.dart';
    import 'package:screenshot/screenshot.dart';
    import 'package:image_gallery_saver/image_gallery_saver.dart';
    import 'package:simple_permissions/simple_permissions.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            // This is the theme of your application.
            //
            // Try running your application with "flutter run". You'll see the
            // application has a blue toolbar. Then, without quitting the app, try
            // changing the primarySwatch below to Colors.green and then invoke
            // "hot reload" (press "r" in the console where you ran "flutter run",
            // or simply save your changes to "hot reload" in a Flutter IDE).
            // Notice that the counter didn't reset back to zero; the application
            // is not restarted.
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Screenshot Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      // This widget is the home page of your application. It is stateful, meaning
      // that it has a State object (defined below) that contains fields that affect
      // how it looks.
    
      // This class is the configuration for the state. It holds the values (in this
      // case the title) provided by the parent (in this case the App widget) and
      // used by the build method of the State. Fields in a Widget subclass are
      // always marked "final".
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
      File _imageFile;
      bool _allowWriteFile = false;
    
      //Create an instance of ScreenshotController
      ScreenshotController screenshotController = ScreenshotController();
    
      void _incrementCounter() {
        setState(() {
          // This call to setState tells the Flutter framework that something has
          // changed in this State, which causes it to rerun the build method below
          // so that the display can reflect the updated values. If we changed
          // _counter without calling setState(), then the build method would not be
          // called again, and so nothing would appear to happen.
          _counter++;
        });
      }
    
      @override
      void initState() {
        super.initState();
        _requestWritePermission();
      }
    
      _requestWritePermission() async {
        PermissionStatus permissionStatus = await SimplePermissions.requestPermission(Permission.WriteExternalStorage);
    
        if (permissionStatus == PermissionStatus.authorized) {
          setState(() {
            _allowWriteFile = true;
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        // This method is rerun every time setState is called, for instance as done
        // by the _incrementCounter method above.
        //
        // The Flutter framework has been optimized to make rerunning build methods
        // fast, so that you can just rebuild anything that needs updating rather
        // than having to individually change instances of widgets.
        return Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
            title: Text(widget.title),
          ),
          body: Container(
            child: new Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Screenshot(
                    controller: screenshotController,
                    child: Column(
                      children: <Widget>[
                        Text(
                          'You have pushed the button this many times:' +
                              _counter.toString(),
                        ),
                        FlutterLogo(),
                      ],
                    ),
                  ),
                  _imageFile != null ? Image.file(_imageFile) : Container(),
                ],
              ),
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              _incrementCounter();
              _imageFile = null;
              screenshotController
                  .capture(delay: Duration(seconds: 3))
                  .then((File image) async {
                print("image path  ${image.path}");
                setState(() {
                  _imageFile = image;
                });
                final result =
                await ImageGallerySaver.saveImage(image.readAsBytesSync());
                print("File Saved to Gallery");
              }).catchError((onError) {
                print(onError);
              });
            },
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    
      _saved(File image) async {
        final result = await ImageGallerySaver.saveImage(image.readAsBytesSync());
        print("File Saved to Gallery");
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-18
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 2014-12-30
      相关资源
      最近更新 更多