如何获取TextWidget onTap的文本

时间:2019-12-30 08:54:15

标签: android ios flutter

我有一个ListView,它在文本小部件中显示日期。在点击文本小部件时,我希望使用字符串形式的文本。我该怎么办?

这是myCode。

 children: <Widget>[
    GestureDetector(
      onTap: () {
         print('OnTapped');
         print(arrayDay[i].toString());
         // get the text of TextWidget here
      },
      child: new Text(
         arrayDay[i].toString(),
         style: new TextStyle(
         fontWeight: FontWeight.w400),
        ),
     ),

3 个答案:

答案 0 :(得分:1)

在点击方法中,您可以从列表中获取数据。所以我在这里发布了一些代码,以便获得更多想法

return ListView.builder(
            itemCount: count,
            itemBuilder: (BuildContext context, int position) {
              return Card(
                color: Colors.white,
                elevation: 2.0,
                child: ListTile(

                  title: Text(this.noteList[position].title,
                    style: titleStyle,
                  ),
                  subtitle: Text(this.noteList[position].date),

                  onTap: () {
                    debugPrint('Note Data '+ this.noteList[position].title);
                    debugPrint('Data '+ 'Here your Data Get'); // you can get data here
                  },
                ),
              ); // Card
            });

答案 1 :(得分:0)

使用ListView.builder并在RowItem中传递数据。

ListView.builder(
        itemBuilder: (context, index) => RowItem( list[index]),
        itemCount: list.length,
      ),

class RowItem extends StatelessWidget {
  final String data;
  RowItem(this.data);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        print(data);
      },
      child: Text(data),
    );
  }
}

答案 2 :(得分:0)

尝试使用ListBuilder,在listBuilder中传递列表,然后在TextWidget上从当前索引获取数据

  child: ListView.builder(
          itemCount: _list.length,
          itemBuilder: (BuildContext context, int index) {
          return listTileCard(index);
          });

         listTileCard(index) {
         return GestureDetector(
            onTap: () {
              print('OnTapped');
              print(_list[index].toString());
              // get the text of TextWidget here
            },
            child: new Text(
              _list[index].toString(),
              style: new TextStyle(
                  fontWeight: FontWeight.w400),
            ),
          )

}