mercredi 8 décembre 2021

Change elevated button color via radio buttons in flutter

I want to change the Elevated button color when I press the radio buttons. 1.button -> red, 2.button -> yellow, 3.button -> green. In the Elevated.stylefrom if condition did not work. Just ternary condition works but it is only for one condition. I want to add 3 conditions. I hope it was clear.

Or do I need to create a model for this?

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:task_shopping_app/const/const.dart';
import 'package:task_shopping_app/screens/city_input_screen.dart';
import 'package:task_shopping_app/screens/weather.dart';

class RadioButton extends StatefulWidget {
  @override
  _RadioButtonState createState() => _RadioButtonState();
}

class _RadioButtonState extends State<RadioButton> {
  int selectedValue = 0;
  final enteredCityInfo = TextEditingController();
  String name = '';
  // if selectedValue and group value matches then radio button will be selected.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          ButtonBar(
            alignment: MainAxisAlignment.center,
            children: <Widget>[
              Radio<int>(
                  value: 1,
                  groupValue: selectedValue,
                  onChanged: (value) => setState(() {
                        selectedValue = value!;
                        print(selectedValue);
                      })),
              Radio<int>(
                  value: 2,
                  groupValue: selectedValue,
                  onChanged: (value) => setState(() {
                        selectedValue = value!;
                        print(selectedValue);
                      })),
              Radio<int>(
                  value: 3,
                  groupValue: selectedValue,
                  onChanged: (value) => setState(() {
                        selectedValue = value!;
                        print(selectedValue);
                      })),
            ],
          ),
          Padding(
            padding: const EdgeInsets.all(25.0),
            child: TextField(
              controller: enteredCityInfo,
            ),
          ),
          ElevatedButton(
            onPressed: () {
              setState(() {
                name = enteredCityInfo.text;
                //Here we want to see user entry for the text field area in the debug console.
                print(name);
                // Get.to(() => WeatherScreen());
              });
            },
            child: Text('Create'),
            style: ElevatedButton.styleFrom(
              primary: selectedValue == 1 ? Colors.red : Colors.yellow,
            ),
          )
        ],
      ),
    );
  }
}

enter code here

Aucun commentaire:

Enregistrer un commentaire