flutter - How to add Strings to a List from a TextFormField in Flutter
问题描述
I don't have a code yet but i want to be able to save data from a textformfield to a list.
I want to get String from a textformfield whenever a comma is detected, eg, adding tags to a post or video
解决方案
我写了一个简单的程序,当它检测到你的文本中有逗号时,它会将文本添加TextFormField
到a 中。ListView
import 'dart:ui';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final List<String> _data = List.empty(growable: true);
final TextEditingController _textFieldController = TextEditingController();
final ScrollController _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("Add to the list!")),
body: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller: _textFieldController,
decoration: InputDecoration(
labelText: 'Enter your text',
),
style: TextStyle(fontSize: 20),
onChanged: (value) {
if (value.contains(','))
Future.delayed(
Duration.zero,
() => setState(() {
final str = value.replaceAll(',', '');
_textFieldController.text = '';
if (str.isNotEmpty) _data.add(str);
}),
).then(
(value) => _scrollController.animateTo(
_scrollController.position.maxScrollExtent + 30,
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOut,
),
);
},
),
SizedBox(height: 20),
Expanded(
child: ListView.builder(
controller: _scrollController,
itemExtent: 30,
cacheExtent: 30,
itemCount: _data.length,
itemBuilder: (context, index) => Text(
_data[index],
style: TextStyle(
fontSize: 20,
fontStyle: FontStyle.italic,
color: Colors.blue[900],
),
),
),
),
],
),
),
),
);
}
}
推荐阅读
- javascript - Discord.js“无法读取未定义的属性‘toLowerCase’”
- angularjs - 如何存储对变量的http angularjs调用响应
- ruby - 无法在 Ubuntu 上加载 Ruby 的 tk
- python - 在另一个 python 模块中检测导入的包
- ios - 如何防止 UITableViewCell 在点击时被视觉取消选择?
- javascript - 为什么 res.rows 未定义?
- django - 尝试使用 django Group 模型创建新组时出错
- multithreading - 缓存一致性与写入同一元素
- javascript - 每次单击 Javascript 中的单个按钮时,我可以创建最多 5 个不同的操作吗?
- rust - 在 Rust 中构建链表