Flutter 按钮 Button 禁用与启用

16 min read
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

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

class _HomePageState extends State<HomePage> {
  // 1
  bool _isAcceptTermsAndConditions = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter App'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Checkbox(
                    value: _isAcceptTermsAndConditions,
                    onChanged: (value) {
                      setState(() {
                        // 2
                        _isAcceptTermsAndConditions = value ?? false;
                      });
                    }),
                Text('I accept the terms and conditions.'),
              ],
            ),
            ElevatedButton(
              // 3
              onPressed: _isAcceptTermsAndConditions
                  ? () {
                      print('Submit');
                    }
                  : null,
              child: Text('Click Me!'),
            ),
          ],
        ),
      ),
    );
  }
}

通过给 onPress 传值 如果 null 按钮为禁用状态

var isEnabled = false

onPressed: isEnabled ? () {}: null