flutter學習之基礎組件(七)
本節主要學習輸入框和選擇控制元件以及日期組件
文章目錄
- flutter學習之基礎組件(七)
- 一、TextField文本輸入框
- 二、Checkbox、CheckboxListTile多選框組件
- 1.Checkbox
- 2.CheckboxListTile
- 三、Radio、RadioListTile單選按鈕組件和Switch開關組件
- 1.Radio
- 2.RadioListTile
- 3.Switch
- 四、混合實作一個學員資訊上報系統
- 五、Flutter日期和時間戳
- 1.flutter自帶日期組件和時間組件
- 2.使用三方日期組件
- 總結
一、TextField文本輸入框
TextField 表單常見屬性:


具體各種實作代碼:
class _FormContentState extends State<FormContent> {
late TextEditingController _username;
var textUsername = "初始值";
@override
void initState() {
super.initState();
_username = new TextEditingController(text: "初始值12312");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("表單演示頁面"),
),
body: Padding(
padding: EdgeInsets.all(20),
child: ListView(
children: [
TextField(),
SizedBox(
height: 10,
),
TextField(
decoration: InputDecoration(
hintText: "請輸入賬號", border: OutlineInputBorder() //設定外部邊框
),
),
SizedBox(
height: 10,
),
TextField(
maxLines: 2,
decoration: InputDecoration(
hintText: "多行文本框", border: OutlineInputBorder() //設定外部邊框
),
),
SizedBox(
height: 10,
),
TextField(
obscureText: true, //設定顯示密碼框
decoration: InputDecoration(
hintText: "密碼框", border: OutlineInputBorder() //設定外部邊框
),
),
SizedBox(
height: 10,
),
TextField(
decoration: InputDecoration(
hintText: "用戶名",
border: OutlineInputBorder(), //設定外部邊框
labelText: "用戶名"),
),
SizedBox(
height: 10,
),
TextField(
decoration: InputDecoration(
hintText: "文本框設定圖示",
icon: Icon(Icons.people),
border: OutlineInputBorder(), //設定外部邊框
),
),
SizedBox(
height: 10,
),
TextField(
decoration: InputDecoration(
hintText: "獲取文本內容",
border: OutlineInputBorder(), //設定外部邊框
),
controller: _username,
onChanged: (value) {
setState(() {
_username.text = value;
});
}),
SizedBox(
height: 20,
),
Container(
height: 40,
width: double.infinity,
child: ElevatedButton(
onPressed: () {
setState(() {
textUsername = _username.text;
});
},
child: Text("獲取文本內容")),
),
SizedBox(
height: 20,
),
Text(textUsername)
],
),
),
);
}
}
二、Checkbox、CheckboxListTile多選框組件
1.Checkbox


2.CheckboxListTile


class CheckBoxContent extends StatefulWidget {
const CheckBoxContent({Key? key}) : super(key: key);
@override
_CheckBoxContentState createState() => _CheckBoxContentState();
}
class _CheckBoxContentState extends State<CheckBoxContent> {
var flag = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("CheckBox演示頁面"),
),
body: Padding(
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Checkbox(
value: flag,
onChanged: (value) {
setState(() {
this.flag = value!;
});
},
checkColor: Colors.white,
activeColor: Colors.red),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text(this.flag ? "選中" : "未選中")],
),
SizedBox(
height: 20,
),
Divider(),
SizedBox(
height: 20,
),
CheckboxListTile(
value: flag,
onChanged: (value) {
setState(() {
this.flag = value!;
});
},
title: Text("選擇"),
subtitle: Text("請選擇"),
secondary: Icon(Icons.home),
)
],
),
),
);
}
}
三、Radio、RadioListTile單選按鈕組件和Switch開關組件
1.Radio

2.RadioListTile

3.Switch


class RadioDemoContent extends StatefulWidget {
const RadioDemoContent({Key? key}) : super(key: key);
@override
_RadioDemoContentState createState() => _RadioDemoContentState();
}
class _RadioDemoContentState extends State<RadioDemoContent> {
var _sex;
var flag = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Radio演示頁面"),
),
body: Container(
alignment: Alignment.center,
child: Column(
children: [
Text("Radio"),
Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("男"),
Radio(
value: 1,
groupValue: this._sex,
onChanged: (value) {
setState(() {
this._sex = value;
});
}),
SizedBox(
width: 20,
),
Text("女"),
Radio(
value: 2,
groupValue: this._sex,
onChanged: (value) {
setState(() {
this._sex = value;
});
}),
],
),
Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("${this._sex}"),
Text(this._sex == 1 ? "男" : "女")
],
),
Divider(),
Text("RadioListTile"),
Divider(),
RadioListTile(
value: 1,
groupValue: this._sex,
onChanged: (v) {
setState(() {
this._sex = v;
});
},
title: Text("選擇1"),
subtitle: Text("請選擇1"),
secondary: Icon(Icons.home),
),
RadioListTile(
value: 2,
groupValue: this._sex,
onChanged: (v) {
setState(() {
this._sex = v;
});
},
title: Text("選擇2"),
subtitle: Text("請選擇2"),
secondary: Icon(Icons.home),
),
RadioListTile(
value: 3,
groupValue: this._sex,
onChanged: (v) {
setState(() {
this._sex = v;
});
},
title: Text("選擇3"),
subtitle: Text("請選擇3"),
secondary: Icon(Icons.home),
),
Divider(),
Text("Switch開關"),
Divider(),
Switch(
value: this.flag,
onChanged: (v) {
setState(() {
this.flag = v;
});
})
],
),
),
);
}
}
四、混合實作一個學員資訊上報系統
通過TextFiled,CheckBoX,Radio實作一個上報資料頁面,效果:

代碼:
class blendContent extends StatefulWidget {
const blendContent({Key? key}) : super(key: key);
@override
_blendContentState createState() => _blendContentState();
}
class _blendContentState extends State<blendContent> {
late String _username;
var _sex;
String data = "";
List hobby = [
{"check": true, "titile": "吃飯"},
{"check": false, "titile": "睡覺"},
{"check": false, "titile": "打豆豆"},
];
void _setRadioChanged(v) {
setState(() {
this._sex = v;
});
}
List<Widget> _gerHobby() {
List<Widget> list = [];
for (var i = 0; i < hobby.length; i++) {
list.add(Text(this.hobby[i]["titile"]+":"));
list.add(Checkbox(
value: this.hobby[i]["check"],
onChanged: (bool? value) {
setState(() {
this.hobby[i]["check"] = value;
});
},
));
}
return list;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("學員資訊上報系統"),
),
body: Container(
padding: EdgeInsets.all(10),
child: Column(
children: [
TextField(
decoration: InputDecoration(
hintText: "請輸入用戶資訊",
border: OutlineInputBorder(), //設定外部邊框
labelText: "用戶名"),
onChanged: (v) {
setState(() {
this._username = v;
});
},
),
Row(
children: [
Text("男:"),
Radio(
value: 1,
groupValue: this._sex,
onChanged: this._setRadioChanged),
SizedBox(
width: 20,
),
Text("女:"),
Radio(
value: 2,
groupValue: this._sex,
onChanged: this._setRadioChanged),
],
),
Column(
children: [
Text("愛好:"),
Row(
children: _gerHobby(),
),
],
),
SizedBox(
height: 20,
),
Container(
width: double.infinity,
height: 40,
child: ElevatedButton(
onPressed: () {
setState(() {
data = "上報成功:姓名:${this._username} 性別:${this._sex} 愛好:${hobby}";
});
},
child: Text("上報資訊"),
),
),
Divider(),
Text(data),
],
),
),
);
}
}
五、Flutter日期和時間戳
獲取當前日期:
var _now = new DateTime.now();
print(_now);
日期轉換成時間戳 13位
var time = _now.microsecondsSinceEpoch;
print(time); //轉換成時間戳 1627454464973662
時間戳轉化成日期:
var dateTime = DateTime.fromMillisecondsSinceEpoch(1627454464973662);
print(dateTime); //時間戳轉時間
1.flutter自帶日期組件和時間組件
flutter的日期組件是showDatePicker ,時間組件是showTimePicker,效果圖如下:

相關代碼:
class SystemDataContent extends StatefulWidget {
const SystemDataContent({Key? key}) : super(key: key);
@override
_SystemDataContentState createState() => _SystemDataContentState();
}
class _SystemDataContentState extends State<SystemDataContent> {
var _now = new DateTime.now();
var _nowTime = TimeOfDay.fromDateTime(new DateTime.now());
_showDataPicker() async {
var result = await showDatePicker(
context: context,
initialDate: _now,
firstDate: DateTime(1980),
lastDate: DateTime(2025),
locale: Locale('zh'),
);
setState(() {
this._now = result!;
});
}
_showTimePicker() async {
var result = await showTimePicker(
context: context,
initialTime: _nowTime,
);
setState(() {
this._nowTime = result!;
});
}
@override
void initState() {
super.initState();
print(_now);
var time = _now.microsecondsSinceEpoch;
print(time); //轉換成時間戳 1627454464973662
var dateTime = DateTime.fromMillisecondsSinceEpoch(1627454464973662);
print(dateTime); //時間戳轉時間
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("系統日期"),
),
body: Padding(
padding: EdgeInsets.all(10),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
//給組件設定點擊事件
InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("${this._now}"),
Icon(Icons.all_inclusive_sharp)
],
),
onTap: () {
_showDataPicker();
},
),
InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("${formatDate(this._now, [yyyy, "年", mm, "月", dd])}"),
Icon(Icons.all_inclusive_sharp)
],
),
onTap: () {
_showDataPicker();
},
),
InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("${this._nowTime.format(context)}"),
Icon(Icons.timelapse)
],
),
onTap: () {
_showTimePicker();
},
),
],
),
),
);
}
}
系統默認的日歷是英文的,想要顯示中文需要實作國際化,實作國際化首先需要在pubspec.yaml檔案的
dependencies下添加:
# 國際化
flutter_localizations:
sdk: flutter
然后在主頁MaterialApp下配置如下代碼:
import 'package:flutter_localizations/flutter_localizations.dart';
//下面兩行配置國際化
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('zh', 'CH'),
const Locale('en', 'US'),
],

再然后在需要實作國際化的控制元件配置相關國際化的代碼:

這樣就實作國際化了
2.使用三方日期組件
先打開三方庫查找網頁https://pub.flutter-io.cn/
然后搜索flutter_datetime_picker并且按照集成檔案,集成到專案中

flutter_datetime_picker: ^1.5.1
效果圖如下:

相關代碼:
class OtherDataContent extends StatefulWidget {
const OtherDataContent({Key? key}) : super(key: key);
@override
_OtherDataContentState createState() => _OtherDataContentState();
}
class _OtherDataContentState extends State<OtherDataContent> {
DateTime _nowDate = new DateTime.now();
TimeOfDay _nowTime = TimeOfDay.fromDateTime(new DateTime.now());
_showDataPicker() {
DatePicker.showDatePicker(context,
showTitleActions: true,
minTime: DateTime(2015, 3, 5),
maxTime: DateTime(2025, 6, 7), onChanged: (date) {
print('change $date');
}, onConfirm: (date) {
setState(() {
this._nowDate = date;
});
}, currentTime: DateTime.now(), locale: LocaleType.zh);
}
_showDataTimePicker() {
DatePicker.showDateTimePicker(context,
showTitleActions: true,
minTime: DateTime(2015, 3, 5),
maxTime: DateTime(2025, 6, 7), onChanged: (date) {
print('change $date');
}, onConfirm: (date) {
setState(() {
this._nowDate = date;
});
}, currentTime: DateTime.now(), locale: LocaleType.zh);
}
_showTimePicker() {
DatePicker.showTimePicker(context,
showTitleActions: true,
onChanged: (date) {
print('change $date');
}, onConfirm: (date) {
setState(() {
this._nowTime = date as TimeOfDay;
});
}, currentTime: DateTime.now(), locale: LocaleType.zh);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("三方日期組件flutter_datetime_picker"),
),
body: Container(
padding: EdgeInsets.all(10),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text("${formatDate(this._nowDate, [yyyy, "-", mm, "-", dd])}"), Icon(Icons.arrow_drop_down)],
),
onTap: _showDataPicker,
),
InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text("${this._nowTime.format(context)}"), Icon(Icons.arrow_drop_down)],
),
onTap: _showTimePicker,
),
InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text("${formatDate(this._nowDate, [yyyy, '-', mm, '-', dd," ",HH, ':', nn, ':', ss])}"), Icon(Icons.arrow_drop_down)],
),
onTap: _showDataTimePicker,
),
],
),
),
),
);
}
}
總結
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/291222.html
標籤:其他
