- static bool? _isChecked=false; //
- static bool _isSwitchChecked=false;
- value必须是static不能动态,且一个可为空一个不可为空。 value不是static 则控件不更新新值。 网上有说用key获取状态,调试过行不通,为null
4.两个控件的 onChanged: (newValue)的(newValue)居然一个取反一个未取反
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
static bool? _isChecked=false;
static bool _isSwitchChecked=false;
final GlobalKey<FormFieldState> key_Switch = GlobalKey();
final GlobalKey<FormFieldState> key_Checkbox = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Switch(
key:key_Switch,
value:_isSwitchChecked,
onChanged:(value){
setState(() {
_isSwitchChecked = value;
});
},
),
Checkbox(
key:key_Checkbox,
value: _isChecked ,
onChanged: (newValue) {
setState(() {
_isChecked = newValue!;
print("aab:${key_Checkbox}");
});
print(_isChecked);
},
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}