【问题标题】:How to retrieve the Image path from carousal that is displayed in flutter如何从颤动中显示的轮播中检索图像路径
【发布时间】:2020-07-29 15:55:18
【问题描述】:

我有一个分享按钮,它应该分享在轮播中显示的图像文件。 如何从显示的轮播中检索图像文件路径? 图像映射如下:

   class ImgView extends StatelessWidget {
      final List<Item> mItems;
      final String title;
      ImageView({this.mItems, @required this.title, Key key})
         

小部件主体的构建如下:

  body: mItems.length == 1
      ? Center(child: Image.file(File(mItems[0].path)))
      : Carousel(
    images: mItems
        .map((MediaItem item) => FileImage(File(item.path)))
        .toList(growable: false),
  ),
);

} }

_sendEmail() async {
        try {

//here I just hard coded the first image file path but i couldn't pass values which are currently displaying in Carousal
    final ByteData bytes = await rootBundle.load(firstfileimagepath);
          await Share.file(
              'esys image', mediaItems[0].title+getFileExtensionFromPath(firstfileimagepath) , bytes.buffer.asUint8List(), 'image/png',
              text: 'My optional text.');
        } catch (e) {
          throw 'Some message';
        }
      }
  
    }

【问题讨论】:

  • 您可以从地图中访问路径。有什么问题?
  • 分享完整代码,不看完整代码就无法判断实际问题。
  • 我已添加完整代码请看代码
  • 我已经回答了你的问题,如果我遗漏了什么,请告诉我。

标签: flutter


【解决方案1】:

我假设你正在使用这个carousel 包。

carousel 包为我们提供了一个属性,它是一个名为onImageChang 的函数,该函数将上一个和当前图像索引作为参数传递,然后您可以使用该函数提供的索引来共享您的图像。

int index = 0;

 body: mediaItems.length == 1
      ? Center(child: Image.file(File(mediaItems[0].path)))
      : Carousel(
    autoplay: false,
    boxFit: BoxFit.contain,
    indicatorBgPadding: 4.0,
    dotSize: 4.0,
    onImageChange: (prev,current) {
      setState(() {
          index = current;
      });
    },
    images: mediaItems
        .map((MediaItem item) => FileImage(File(item.path)))
        .toList(growable: false),
  ),
);

// now you can use your index to get the current image index and use that to share images.

final ByteData bytes = await rootBundle.load(mediaItems[index].path);
      await Share.file(
          'esys image', mediaItems[index].title+getFileExtensionFromPath(mediaItems[index].path) , bytes.buffer.asUint8List(), 'image/png',
          text: 'My optional text.');
    } catch (e) {
      throw 'Could not send mail or no default mail application is present';
    }
  }
  String getFileExtensionFromPath(String path) {
    return path.substring(path.lastIndexOf('.'));
  }
}

【讨论】:

  • 感谢您的回答,但我的小部件是无状态的,并且在 setState() 处出现错误有没有办法解决这个问题我试图使我的小部件有状态,但仍然存在错误。很抱歉问这些问题,我对 Flutter 有非常基本的了解
  • 只需将无状态小部件转换为有状态小部件即可。将其转换为有状态小部件后出现什么错误?
  • 表示没有为ImgView定义setState()方法
  • 非常感谢你救了我
猜你喜欢
  • 2014-08-28
  • 2020-10-11
  • 2021-04-12
  • 2021-03-05
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 2018-12-14
相关资源
最近更新 更多