Flutter | 如何在AlertDialog中更改按钮的颜色?

4

大家好! 我请求帮助。 我有一个StatefulWidget,其中我调用AlertDialog,在initState和setState中创建,但是仅当我关闭并重新打开AlertDialog时,按钮颜色才会更改,而不是立即单击后。 我需要找出如何重新绘制此窗口或其他方法。 还有另一个问题,如果我将FloatingActionButton放在单独的文件中,因此在单独的StatefulWidget中,当我点击“添加”时,列表本身不会更新,但是如果我将FloatingActionButton放回主页,一切都可以正常工作。但那是另一个问题)请求帮助ElevatedButton“Work”内的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'),
        ),
      ),
    );
  }
}
3个回答

3

将您想要更改的小部件包装在StatefulBuilder中,在您的情况下是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)),
    );
  }),

2
您当前的setState仅适用于HomeScreen上下文。您需要将对话框分离为一个stateful widget,以使setState在对话框上起作用。
这里有一个可行的示例(尝试在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"),
        ),
      ],
    );
  }
}

哦,我明白了,谢谢! - Dedserv

0

对话框不会使用set state自动更新。因此,您必须使用其他状态管理工具,如GetX或Provider来更改小部件的状态。其次,它还将帮助使用按钮更新要更新的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接