Home > Net >  How to change the text color which is in a different widget on switch with a flutter provider?
How to change the text color which is in a different widget on switch with a flutter provider?

Time:11-11

How to change the text color which is in a different widget on switch with a flutter provider?

When switch is on change text color to red else change to green. Bu don't merge first and second widgets.

When clicked switch button change other widget's text.

`

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

void main() => runApp(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 StatefulWidget {
  const SwitchExample({super.key});

  @override
  State<SwitchExample> createState() => _SwitchExampleState();
}

class _SwitchExampleState extends State<SwitchExample> {
  bool light = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Switch(
          // This bool value toggles the switch.
          value: light,
          activeColor: Colors.red,
          onChanged: (bool value) {
            // This is called when the user toggles the switch.
            setState(() {
              light = value;
            });
          },
        ),
        MyText()
      ],
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return const Text('Change my color',
        style: TextStyle(color: Colors.green));
  }
}

`

CodePudding user response:

The easiest way would be to pass the color down into the constructor of MyText widget, since MyText widget is being built as a child of SwitchExample which is handling the switch state.

import 'package:provider/provider.dart';

void main() => runApp(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 StatefulWidget {
  const SwitchExample({super.key});

  @override
  State<SwitchExample> createState() => _SwitchExampleState();
}

class _SwitchExampleState extends State<SwitchExample> {
  bool light = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Switch(
          // This bool value toggles the switch.
          value: light,
          activeColor: Colors.red,
          onChanged: (bool value) {
            // This is called when the user toggles the switch.
            setState(() {
              light = value;
            });
          },
        ),
        MyText(light ? Colors.green : Colors.blue)
      ],
    );
  }
}

class MyText extends StatelessWidget {
  final Color color;
  const MyText(this.color, {super.key});

  @override
  Widget build(BuildContext context) {
    return Text('Change my color',
        style: TextStyle(color: color));
  }
}

But, if you wanted to use provider so that MyText could be a child widget anywhere below the provider widget in the tree you could use Provider with a ChangeNotifier:

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

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

class ColorModel extends ChangeNotifier {
  Color color = Colors.green;
  void setColor(Color color) {
    this.color = color;
    notifyListeners();
  }
}

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

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

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

  @override
  State<SwitchExample> createState() => _SwitchExampleState();
}

class _SwitchExampleState extends State<SwitchExample> {
  bool light = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Switch(
          // This bool value toggles the switch.
          value: light,
          activeColor: Colors.red,
          onChanged: (bool value) {
            // This is called when the user toggles the switch.
            setState(() {
              light = value;
            });
            Provider.of<ColorModel>(context, listen: false)
                .setColor(value ? Colors.green : Colors.blue);
          },
        ),
        MyText()
      ],
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Consumer<ColorModel>(builder: (context, state, _) {
      return Text('Change my color', style: TextStyle(color: state.color));
    });
  }
}

Check out flutter's docs for more info: https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple

  • Related