iOS風(fēng)格的彈窗直接貼代碼。
import 'package:flutter/cupertino.dart'; // iOS風(fēng)格組件
import 'package:flutter/material.dart';
Future<String?> showTextAlertDialog(
{required BuildContext context,
String? defaultValue,
String? title,
String? placeholder,
String? okText,
String? cancelText}) async {
TextEditingController controller = TextEditingController();
controller.text = defaultValue ?? "";
final FocusNode focusNode = FocusNode();
return await showDialog<String>(
context: context,
builder: (context) {
WidgetsBinding.instance.addPostFrameCallback((_) {
FocusScope.of(context).requestFocus(focusNode);
});
return CupertinoAlertDialog(
title: title == null ? null : Text(title),
content: Padding(
padding: const EdgeInsets.all(5),
child: CupertinoTextField(
controller: controller,
focusNode: focusNode,
placeholder: placeholder,
),
),
actions: <Widget>[
TextButton(
child: Text(cancelText ?? 'Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text(okText ?? 'OK'),
onPressed: () {
Navigator.of(context).pop(controller.text);
},
),
],
);
});
}
使用方式:
Widget build(BuildContext context) {
return Center(
child: OutlinedButton.icon(
onPressed: () async {
String? text = await showTextAlertDialog(
context: context, title: "添加");
print("text: $text");
},
icon: const Icon(Icons.add),
label: const Text("添加")));
}