[英]Flutter: how to get index value using VoidCallBack onTap function
[英]how to return value from onTap function in flutter
我是編程新手 flutter。我在從 onTap function 返回值時遇到錯誤。錯誤顯示返回類型“int”不是“void”,這是閉包上下文所要求的。 我正在從 API 獲取圖像並將它們顯示在屏幕上。 我希望當有人點擊圖像時,圖像 ID 應該存儲在一個變量中,該變量將在另一個屏幕上使用。 我正在使用 Gesturedetector 的 onTap function 來獲取圖像 ID,我成功將該 ID 打印到終端並將其存儲在一個變量中,但我無法返回該變量並想在另一個屏幕上使用該變量。 任何人,請幫助我返回該變量的值。 我的代碼如下
import 'package:flutter/material.dart';
import 'Service.dart';
import 'View2.dart';
import 'models/memegenetor_model.dart';
class template_view extends StatefulWidget {
template_view({Key? key}) : super(key: key);
@override
State<template_view> createState() => _template_viewState();
}
class _template_viewState extends State<template_view> {
late Future<Memes_Model> futureScore;
@override
void initState() {
super.initState();
futureScore = ApiService().GetTemplates();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: FutureBuilder<Memes_Model>(
future: futureScore,
builder: (context, snapshot) {
if (snapshot.data != null) {
return ListView.builder(
itemCount: snapshot.data!.data.memes.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.only(left: 20, right: 20, top: 20),
child: Container(
color: Colors.red,
width: MediaQuery.of(context).size.width,
//height: 100,
child: GestureDetector(
onTap: (){
int tempid=snapshot.data!.data.memes[index].id;
return tempid;
},
child: Column(
children: [
Image.network(
"${snapshot.data!.data.memes[index].url}",
width: MediaQuery.of(context).size.width * 0.2),
],
),
)),
);
});
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
));
}
}
您不能從onTap
返回值。 在你的 class 中新建一個 state。
class _template_viewState extends State<template_view> {
int? tempid = null; // or int tempid = -1;
// ...
}
onTap
應該是這樣的:
onTap: () {
tempid = snapshot.data!.data.memes[index].id; // use setState if require
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.