可以通过点击触发Flutter GridTile?

问题描述 投票:3回答:1

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

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),
  ),
);
}
}
gridview dart flutter
1个回答
9
投票

您可以将GridTile包装在InkResponseGestureDetector中并传递一个函数,以便在单击时调用

例:

// 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),
)

希望有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.