TextInput用法
时间: 2024-02-06 08:04:19 浏览: 35
TextInput是一个基础的widget,用于接收用户输入的文本。它没有UI外观,因此你需要自己构建UI来包装它。
以下是一个简单的示例,演示如何使用TextInput:
```dart
import 'package:flutter/material.dart';
class MyTextInput extends StatefulWidget {
@override
_MyTextInputState createState() => _MyTextInputState();
}
class _MyTextInputState extends State<MyTextInput> {
final myController = TextEditingController();
@override
void dispose() {
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Text Input'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Enter some text:',
),
SizedBox(height: 10),
Container(
width: 300,
child: TextField(
controller: myController,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Type something here',
),
),
),
SizedBox(height: 10),
RaisedButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Your input'),
content: Text(myController.text),
actions: <Widget>[
FlatButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
},
child: Text('Show input'),
),
],
),
),
);
}
}
```
在这个示例中,我们创建了一个文本输入框,当用户输入文本时,它将被存储在TextEditingController中。当用户点击“Show input”按钮时,我们将会显示一个AlertDialog,其中包含用户输入的文本。
需要注意的是,在使用完TextInput后,我们需要调用TextEditingController的dispose()方法来释放资源。在StatefulWidget中,我们通常会在State的dispose()方法中调用它。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)