web-dev-qa-db-ja.com

Flutter GridTileはタップでトリガーできますか?

フラッターアプリを作成し、画像ピッカーを使用して、グリッドタイルで画像配列をループすることで画像を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),
  ),
);
}
}
12
Raditha

GridTileInkResponseまたはGestureDetectorでラップし、クリックされたときに呼び出される関数を渡すだけです。

例:

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

お役に立てば幸いです。

14
Hemanth Raj

グリッドビルダーを使用することもできます

child: new GridView.builder(
          itemCount: 20,
          gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2),
          itemBuilder: (BuildContext context, int index) {
            return new Card(
              child: new InkResponse(
                 child: Image.asset('assets/whats-best-for-your-app-objective-cswift.jpg'),
                onTap: (){
                  print(index);
                },
              ),
            );
          }),
1
Anil Kumar