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

能否为多个InkWell共享MaterialStatesController实现状态联动?

共享MaterialStatesController实现InkWell状态联动

完全可以通过共享同一个MaterialStatesController实现两个InkWell的状态联动,这是官方推荐的同步组件状态的方案之一。

实现示例代码

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    // 创建共享的MaterialStatesController
    final statesController = MaterialStatesController();

    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 圆形InkWell,绑定共享控制器
              InkWell(
                statesController: statesController,
                borderRadius: BorderRadius.circular(50),
                onTap: () {},
                child: const SizedBox(
                  width: 100,
                  height: 100,
                  child: Center(child: Text('圆形按钮')),
                ),
              ),
              const SizedBox(height: 20),
              // 条形InkWell,绑定同一个共享控制器
              InkWell(
                statesController: statesController,
                borderRadius: BorderRadius.circular(8),
                onTap: () {},
                child: const SizedBox(
                  width: 200,
                  height: 60,
                  child: Center(child: Text('条形按钮')),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

关键说明

  • 只需创建一个MaterialStatesController实例,将其赋值给所有需要联动状态的InkWell的statesController参数
  • 当任意一个InkWell触发按压(MaterialState.pressed)、悬停等状态变化时,控制器会自动同步状态到所有关联组件,实现完全联动的视觉反馈
  • 这种方式无需手动监听状态变化或调用setState,状态同步逻辑由Material组件库内部自动处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:35:26