You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何从onTap函数传递值至其他页面?解决返回类型错误

问题解决:GestureDetector onTap返回值错误与页面传参

错误原因

GestureDetector的onTap是void类型的回调函数,它不需要返回任何值,你在里面写return tempid(返回int类型),会触发类型不匹配的错误,这就是报错提示The return type 'int' isn't a 'void'的根本原因。

解决方案

要实现点击图片传递ID到其他页面,不需要从onTap返回值,直接在onTap回调里使用Navigator.push跳转到目标页面,并把ID作为参数传递过去即可。具体步骤如下:

  1. 修改目标页面(View2):让它支持接收ID参数
    先给View2添加接收ID的构造函数,示例代码:

    class View2 extends StatelessWidget {
      final int imageId;
      const View2({Key? key, required this.imageId}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        // 这里可以直接使用imageId做后续业务处理
        return Scaffold(
          appBar: AppBar(title: const Text("详情页")),
          body: Center(child: Text("选中的图片ID: $imageId")),
        );
      }
    }
    
  2. 修正template_view中的onTap逻辑:移除return语句,替换为页面跳转代码
    把原来的onTap代码替换成以下内容:

    onTap: () {
      int tempid = snapshot.data!.data.memes[index].id;
      // 跳转到View2并传递ID参数
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => View2(imageId: tempid),
        ),
      );
    },
    

修改后的完整代码

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,
                      child: GestureDetector(
                        onTap: () {
                          int tempid = snapshot.data!.data.memes[index].id;
                          // 跳转页面并传递ID
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => View2(imageId: 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();
        },
      ),
    ));
  }
}

补充说明

如果不需要立即跳转,只是想先保存选中的ID到变量,后续再使用,可以在_template_viewState类里定义一个变量,然后用setState更新:

// 在_state类里添加变量
int? selectedImageId;

// onTap里的代码修改为
onTap: () {
  setState(() {
    selectedImageId = snapshot.data!.data.memes[index].id;
  });
  // 后续可在其他操作(比如按钮点击)中使用selectedImageId
},

内容的提问来源于stack exchange,提问作者Dont Know

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:40:27