Flutter基礎(chǔ)組件(3-3)-ListView數(shù)item中的點(diǎn)擊

ListView的數(shù)據(jù)展示和數(shù)據(jù)刷新、加載更多我們都已經(jīng)明白了,ListView的點(diǎn)擊也是一個需要講解的東西.
先寫一個大的框架方便后期使用:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter App'),),
         body: HomePage(),
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: 30,
      itemBuilder:_buildItem,
      itemExtent: 60,
    );
  }
}

1.ListView中item的點(diǎn)擊事件

在item 上增加FlatButton

Widget _buildItem(BuildContext context,int index){
  return FlatButton(
    onPressed: () => print(index),
    child: Card(
      child: Center(
        child: Text('$index'),
      ),
    ),
  );
}

ListView中的item采用的是FlatButton,這樣做的目的是方便編寫點(diǎn)擊事件,()=> 符號表示傳遞的是回調(diào)函數(shù),不使用的話表示直接執(zhí)行這個函數(shù).

2.用GestureDetector增加手勢的點(diǎn)擊事件

使用GestureDetector 手勢檢測器 可以給 widget添加點(diǎn)擊事件
示例代碼如下:

Widget _buildItem(BuildContext context,int index){
  return Container(
    height: 60,
    color: Colors.cyan,
    child: GestureDetector(
      child: Container(
        margin: EdgeInsets.all(10),
        padding: EdgeInsets.all(10),
        color: Colors.yellow,
        child: Text('123'),
      ),
      onTap: (){
        print('haha');
      },
    ),
  );
}
                            想了解更多Flutter學(xué)習(xí)知識請聯(lián)系:QQ(814299221)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容