簡體   English   中英

Flutter|如何改變AlertDialog里面按鈕的顏色?

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

每個人。 我正在尋求幫助,我有一個 StatefulWidget,我在其中調用 AlertDialog,創建了 initState 和 setState,但是只有當我關閉並重新打開 AlertDialog 時按鈕顏色才會改變。 單擊時不會立即。 我需要弄清楚如何重繪這個 window 或其他方式,還有另一個問題,如果我將 FloatingActionButton 放在一個單獨的文件中,因此放在一個單獨的 StatefulWidget 中,當我單擊添加時列表本身不會更新,但是如果我將 FloatingActionButton 放回主頁。 一切正常。 但這是一個額外的問題)關於 AlertDialog 內的 ElevatedButton“工作”的大量幫助請求。

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'),
        ),
      ),
    );
  }
}

您當前的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"),
        ),
      ],
    );
  }
}

在您的案例中將要更改的小部件包裝在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)),
    );
  }),

該對話框不會使用設置 state 自行更新。因此您必須使用其他 state 管理,如 GetX 或 Provider 來更改小部件的 state。 其次,它還有助於使用按鈕更新您要更新的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM