在日常开发的时候,我们会遇到勾选协议
的需求,这个需求在Flutter
中,我们可以通过Checkbox
组件来实现。这篇博客分享一下,我对Checkbox
组件的使用,希望对看文章的小伙伴有所帮助。
Checkbox的示例的代码
bool checkValue = false;
Checkbox(
value: checkValue,
onChanged: (value) {
setState(() {
checkValue = value!;
});
},
activeColor: Colors.blue,
),
效果图:
属性说明
默认的效果,选中
或者未选中
:
value:false,
点击事件回调:
onChanged: (value) {},
选中的颜色:
activeColor: Colors.blue,
完整的代码
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: 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({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool checkValue = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
child: Checkbox(
value: checkValue,
onChanged: (value) {
setState(() {
checkValue = value!;
});
},
activeColor: Colors.blue,
),
),
);
}
}
这个代码可以直接复制到编译器中运行,感兴趣可以直接复制使用。