Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter|How to change the colour of the button inside AlertDialog?

Tags:

flutter

dart

everyone! I'm begging for help. I have a StatefulWidget in which I call AlertDialog, created initState and setState, but button colour changes only if I close and reopen AlertDialog, not immediately when clicked. I need to figure out how to redraw this window or some other way. There's another problem, if I put the FloatingActionButton in a separate file and therefore in a separate StatefulWidget, the list itself doesn't update when I click Add, but if I put the FloatingActionButton back in the homepage, everything works. But that's an additional question) A big request for help with the ElevatedButton "Work" inside the AlertDialog.

class HomeScreen extends StatefulWidget {

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  late String _addField;
  late IconData _selectedValue;
  late bool _active;

  @override
  void initState() {
    _addField = 'Pusto';
    _active = false;
    _selectedValue = Icons.delete_forever_outlined;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Padding(
          padding: const EdgeInsets.only(left: 8, right: 8),
          child: Column(children: [
            ActiveTaskInfo(
              task: tasks.first,
            ),
            const TextWidget(),
            Expanded(child: TasksList()),
          ]),
        ),
        //bottomNavigationBar: const BottomBar(),
        //floatingActionButton: FloatingButton(),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: const Text('Add Task'),
                    content: TextField(onChanged: (String value) {
                      _addField = value;
                    }),
                    actions: [
                      DropdownButton<IconData>(
                        value: _selectedValue,
                        onChanged: (IconData? newValue) {
                          setState(() {
                            _selectedValue = newValue!;
                          });
                        },
                        items: dropdownItems,
                      ),
                      ElevatedButton(
                          onPressed: () {
                            setState(() {
                              tasks.addAll({
                                TaskData(
                                    taskName: _addField,
                                    tagNameOne: 'Work',
                                    tagNameTwo: 'Rasion Project',
                                    icon: _selectedValue,
                                    taskTime: '00:32:10')
                              });
                              decorations.addAll({
                                TaskTagsDecorations(
                                    firstTagTextColor: const Color(0xffFD5B71),
                                    secondTagTextColor: const Color(0xff9B51E0),
                                    firstTagColor: const Color(0xff1F0D20),
                                    secondTagColor: const Color(0xff150C2B),
                                    iconColor: const Color(0xff7012CF))
                              });
                            });
                            Navigator.of(context).pop();
                          },
                          child: const Text('Add')),
                      ElevatedButton(
                        onPressed: () {
                          setState(() {
                            _active = !_active;
                          });
                        },
                        child: Text('Work'),
                       style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.all(_active ? Colors.blue : Colors.red)
                          ),
                        ),
                    ],
                  );
                });
          },
          child: const Text('Add'),
        ),
      ),
    );
  }
}
like image 792
Dedserv Avatar asked Sep 14 '25 12:09

Dedserv


2 Answers

Wrap the widget you want to change inside StatefulBuilder in your case Elevated Button

StatefulBuilder(builder: (context, myState) {
    return ElevatedButton(
      onPressed: () {
        myState(() {
          _active = !_active;
        });
      },
      child: Text('Work'),
      style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(
              _active ? Colors.blue : Colors.red)),
    );
  }),
like image 93
Vishal Agrawal Avatar answered Sep 17 '25 04:09

Vishal Agrawal


Your current setState is only working for HomeScreen context. You need to separate the dialog as a stateful widget to make setState working on the dialog.

Here a working example for it (Try to run it in dartpad.dev):

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Home Page")),
      body: const Center(child: Text('Home Page Content')),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) => const MyAlertDialog(),
          );
        },
        tooltip: 'Dialog',
        child: const Icon(Icons.add),
      ),
    );
  }
}

class MyAlertDialog extends StatefulWidget {
  const MyAlertDialog({Key? key}) : super(key: key);

  @override
  State<MyAlertDialog> createState() => _MyAlertDialogState();
}

class _MyAlertDialogState extends State<MyAlertDialog> {
  bool _isChanged = false;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text("Dialog"),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: const [Text("Dialog content")],
      ),
      actions: [
        ElevatedButton(
          style: ElevatedButton.styleFrom(
            primary: _isChanged ? Colors.blue : Colors.green,
          ),
          onPressed: () {
            setState(() => _isChanged = !_isChanged);
          },
          child: const Text("Change color"),
        ),
      ],
    );
  }
}
like image 26
ישו אוהב אותך Avatar answered Sep 17 '25 06:09

ישו אוהב אותך