How to refresh an AlertDialog in Flutter?

前端 未结 5 2305
萌比男神i
萌比男神i 2020-11-27 13:54

Currently, I have an AlertDialog with an IconButton. The user can click on the IconButton, I have two colors for each click. The problem is that I

5条回答
  •  無奈伤痛
    2020-11-27 15:01

    This is because you need to put your AlertDialog in its own StatefulWidget and move all state manipulation logic on the color there.

    Update:

    void main() => runApp(MaterialApp(home: Home()));
    
    class Home extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: Center(
                child: RaisedButton(
          child: Text('Open Dialog'),
          onPressed: () {
            showDialog(
                context: context,
                builder: (_) {
                  return MyDialog();
                });
          },
        )));
      }
    }
    
    class MyDialog extends StatefulWidget {
      @override
      _MyDialogState createState() => new _MyDialogState();
    }
    
    class _MyDialogState extends State {
      Color _c = Colors.redAccent;
      @override
      Widget build(BuildContext context) {
        return AlertDialog(
          content: Container(
            color: _c,
            height: 20.0,
            width: 20.0,
          ),
          actions: [
            FlatButton(
                child: Text('Switch'),
                onPressed: () => setState(() {
                      _c == Colors.redAccent
                          ? _c = Colors.blueAccent
                          : _c = Colors.redAccent;
                    }))
          ],
        );
      }
    }
    

提交回复
热议问题