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

如何为Flutter自定义可复用按钮配置不同跳转路由与显示名称

解决方案

1. 修正GlowingButton组件代码

现有代码存在重复定义onTapDown事件、路由跳转语法错误、未渲染按钮文本的问题,修正后代码如下:

import 'package:flutter/material.dart';

class GlowingButton extends StatefulWidget {
  final Color color1;
  final Color color2;
  // 明确指定参数类型,必填参数加required
  final String buttonName;
  final String routeName;

  const GlowingButton({
    Key? key,
    this.color1 = Colors.brown,
    this.color2 = Colors.white10,
    required this.buttonName,
    required this.routeName,
  }) : super(key: key);

  @override
  _GlowingButtonState createState() => _GlowingButtonState();
}

class _GlowingButtonState extends State<GlowingButton> {
  bool glowing = true;
  double scale = 1.0;

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return GestureDetector(
      onTapUp: (val) async {
        setState(() {
          glowing = false;
          scale = 1.0;
        });
      },
      onTapDown: (val) async {
        setState(() {
          glowing = true;
          scale = 1.1;
        });
        await Future.delayed(const Duration(milliseconds: 300));
        // 修正路由跳转语法,直接传入路由名即可
        await Navigator.pushNamed(context, widget.routeName);
        setState(() {});
      },
      // 补充按钮UI渲染逻辑,保留你原有发光效果的同时显示按钮文本
      child: Transform.scale(
        scale: scale,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
          decoration: BoxDecoration(
            gradient: LinearGradient(colors: [widget.color1, widget.color2]),
            borderRadius: BorderRadius.circular(8),
            boxShadow: glowing
                ? [
                    BoxShadow(
                      color: widget.color1.withOpacity(0.6),
                      blurRadius: 12,
                      spreadRadius: 2,
                    )
                  ]
                : null,
          ),
          child: Text(
            widget.buttonName,
            style: const TextStyle(color: Colors.white, fontSize: 16),
          ),
        ),
      ),
    );
  }
}

2. 配置全局路由表

在项目根MaterialApp中注册所有需要跳转的页面路由:

MaterialApp(
  title: '演示项目',
  // 注册路由表,key为路由名,value为对应页面
  routes: {
    '/home': (context) => const HomePage(),
    '/settings': (context) => const SettingsPage(),
    '/profile': (context) => const ProfilePage(),
  },
  initialRoute: '/home',
);

3. 多场景复用组件

在任意需要按钮的页面,直接传入对应按钮名称和路由名即可适配不同场景:

// 跳转到设置页的按钮
GlowingButton(
  buttonName: '进入设置',
  routeName: '/settings',
)

// 跳转到个人中心的按钮,还可自定义配色
GlowingButton(
  buttonName: '查看个人中心',
  routeName: '/profile',
  color1: Colors.blue,
  color2: Colors.lightBlueAccent,
)

效果示意图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:51:02