0

I Created an Rgb Slider in a flutter. and I passed the value of sliders in RGB colors when I press the Button the Color Got changed. But I Want to do it Without a button. I Mean slide the number on the slider and it should be Changed automatically instant.

I am curious to know how this thing gonna work!

But When I passed the variable in Bgcolor this error is coming

Below is my Main. dart

import 'package:flutter/material.dart';

void main() {
  runApp(MyApps());
}

class MyApps extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApps> {
  @override
  bool valueSwitch = false;
  int red = 1;
  int green = 1;
  int blue = 1;
  Color Bgcolor = Color.fromRGBO(red,green,blue, 1.0);



  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Bgcolor,
        appBar: AppBar(
          title: Text('Slider'),
        ),
        body: Column(
          children: [
            ElevatedButton(onPressed: (){
              setState(() {
                Bgcolor = Color.fromRGBO(red, green, blue, 1.0);
              });
            }, child: Text('Apply')),
            Switch(
                value: valueSwitch,
                
                onChanged: (value) {
                  valueSwitch = value;

                  setState(() {});
                }),
            Slider(
                min: 0,
                max: 255,
                value: red.toDouble(),
                onChanged: (value) {
                  red = value.toInt();

                  setState(() {});
                }),
            Slider(
                min: 0,
                max: 255,
                value: green.toDouble(),
                onChanged: (value) {
                  green = value.toInt();

                  setState(() {});
                }),
            Slider(
                min: 0,
                max: 255,
                value: blue.toDouble(),
                onChanged: (value) {
                  blue = value.toInt();

                  setState(() {});
                }),
            Text('RGB($red,$green,$blue )',style: TextStyle(color: Colors.white),),
          ],
        ),
      ),
    );
  }
}

Here is Output:

MindCoder
  • 74
  • 12

1 Answers1

1

You can use initState method:

int red = 1;
int green = 1;
int blue = 1;
late Color Bgcolor;

@override
void initState() {
  super.initState();
  Bgcolor = Color.fromRGBO(red, green, blue, 1.0);
}
Hazar Belge
  • 1,009
  • 4
  • 20