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

如何用Flutter Provider实现开关切换时修改不同Widget的文字颜色

实现开关控制独立Widget文字颜色的解决方案

要实现开关状态控制独立Widget的文字颜色,我们可以利用provider包实现跨Widget的状态共享,既保证两个Widget独立,又能完成状态联动。以下是修改后的完整代码:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// 状态管理类,封装开关状态
class SwitchState extends ChangeNotifier {
  bool _light = false;

  bool get light => _light;

  void toggleLight() {
    _light = !_light;
    notifyListeners(); // 通知所有依赖组件更新状态
  }
}

void main() => runApp(
      // 全局提供状态实例
      ChangeNotifierProvider(
        create: (context) => SwitchState(),
        child: const SwitchApp(),
      ),
    );

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Switch Sample')),
        body: const Center(
          child: SwitchExample(),
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    final switchState = Provider.of<SwitchState>(context);
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Switch(
          value: switchState.light,
          activeColor: Colors.red,
          onChanged: (bool value) {
            switchState.toggleLight();
          },
        ),
        const MyText()
      ],
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    final switchState = Provider.of<SwitchState>(context);
    return Text(
      'Change my color',
      style: TextStyle(
        color: switchState.light ? Colors.red : Colors.green,
      ),
    );
  }
}

关键修改说明:

  1. 新增SwitchState状态类:继承ChangeNotifier,封装开关状态和切换方法,状态变更时通过notifyListeners()通知所有依赖组件更新。
  2. 全局注入状态:在main方法中用ChangeNotifierProvider包裹根组件,让整个应用能访问到状态实例。
  3. 开关组件绑定状态:SwitchExample通过Provider.of获取状态,将开关的value与状态绑定,点击时调用状态切换方法。
  4. 文字组件动态设置颜色:MyText同样获取状态,根据开关状态动态设置文字颜色——开启时为红色,关闭时为绿色。

这种方式既保持了两个Widget的独立性,又实现了状态的跨组件联动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:01:25