Flutter GridTile 可以通过点击触发吗? [英] Flutter GridTile can be triggered with tap?

查看:12
本文介绍了Flutter GridTile 可以通过点击触发吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 flutter 应用程序并使用图像选择器将图像作为 gridView 放置到中心,并使用网格图块循环图像数组.是否可以在点击 gridTile 时触发它?下面是来自 main.dart 的代码,用于将图像添加到数组和网格视图中.

I have created a flutter app and used the image-picker to get images to the center as a gridView with looping the image array with grid tiles.Is it possible to trigger the gridTile when it is tapped? Below is the code from the main.dart for getting the image adding it to an array and to a grid view.

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
File _imageFile;
List<File> _imageList=[];

getImage() async {
var _fileName = await ImagePicker.pickImage();
setState(() {
  _imageFile = _fileName;
  _imageList.add(_imageFile);
});
}

 removeImage(int index){
  setState((){
  _imageList.removeAt(index);
});
}
 @override
 Widget build(BuildContext context) {

 return new Scaffold(
  appBar: new AppBar(

    title: new Text(widget.title),
  ),
  body: new Center(

    child:_imageList.length == 0
        ? new Text('No image selected.')
        :new GridView.count(
        crossAxisCount: 4,
        childAspectRatio: 1.0,
        padding: const EdgeInsets.all(4.0),
        mainAxisSpacing: 4.0,
        crossAxisSpacing: 4.0,
        children: _imageList.map((File file) {
          return new GridTile(

              child: new Image.file(file, fit: BoxFit.cover,));

        }).toList()),
  ),

  floatingActionButton: new FloatingActionButton(
    onPressed:getImage,
    tooltip: 'Pick Image',
    child: new Icon(Icons.add_a_photo),
  ),
);
}
}

推荐答案

您可以将 GridTile 包装在 InkResponseGestureDetector 中并传递点击时要调用的函数

You can just wrap the GridTile in an InkResponse or GestureDetector and pass a function to be invoked when clicked

示例:

// Function to be called on click
void _onTileClicked(int index){
  debugPrint("You tapped on item $index");
}

// Get grid tiles
List<Widget> _getTiles(List<File> iconList) {
  final List<Widget> tiles = <Widget>[];
  for (int i = 0; i < iconList.length; i++) {
    tiles.add(new GridTile(
        child: new InkResponse(
      enableFeedback: true,
      child: new Image.file(iconList[i], fit: BoxFit.cover,),
      onTap: () => _onTileClicked(i),
    )));
  }
  return tiles;
}


// GridView
new GridView.count(
  crossAxisCount: 4,
  childAspectRatio: 1.0,
  padding: const EdgeInsets.all(4.0),
  mainAxisSpacing: 4.0,
  crossAxisSpacing: 4.0,
  children: _getTiles(_imageList),
)

希望有帮助!

这篇关于Flutter GridTile 可以通过点击触发吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆