flutter - 如何从用户输入中计算文本字符串中的单词数
问题描述
我开始学习 Dart 和 Flutter 并且对一个应用程序有问题。我正在尝试编写一个应用程序来计算用户输入的文本字符串中的单词数。我为此编写了 countWords 函数,但我不明白如何正确地将文本字符串发送到该函数。有人可以向我解释如何执行此操作并更正我的代码吗?
import 'package:flutter/material.dart';
import 'dart:convert';
class MyForm extends StatefulWidget {
@override
State<StatefulWidget> createState() => MyFormState();
}
class MyFormState extends State {
final _formKey = GlobalKey<FormState>();
final myController = TextEditingController();
int words_num = 0;
void countWords() {
var regExp = new RegExp(r"\w+(\'\w+)?");
int wordscount = regExp.allMatches(myController.text); //here I have trouble
setState(() {
words_num = wordscount;
});
}
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(10.0),
child: new Form(
key: _formKey,
child: new Column(
children: <Widget>[
new Text(
'Text string:',
style: TextStyle(fontSize: 20.0),
),
new TextFormField(
decoration:
InputDecoration(labelText: 'Enter your text string'),
controller: myController,
),
new SizedBox(height: 20.0),
new RaisedButton(
onPressed: () {
countWords();
},
child: Text('Count words'),
color: Colors.blue,
textColor: Colors.white,
),
new SizedBox(height: 20.0),
new Text(
'Number of words: $words_num',
style: TextStyle(fontSize: 20.0),
),
],
)));
}
}
void main() => runApp(new MaterialApp(
debugShowCheckedModeBanner: false,
home: new Scaffold(
appBar: new AppBar(title: new Text('Count words app')),
body: new MyForm())));
解决方案
推荐阅读
- python - Python:如何将一个自定义包添加到另一个自定义包中?
- tensorflow - 无法设置 trainable=False 以冻结 TensorFlow 中的某些层
- api - 尝试在 API 响应中提取满足某些过滤条件的元素时,空手道 json 路径过滤器不起作用
- sql-server - 从早上 7:00 开始按 24 小时时段分组
- amazon-dynamodb - Alexa SDK V2 高低游戏无法像教程中所说的那样工作
- mysql - 列出 SQL 中 2 列值的 Max(difference)
- android - Android“在xxx包中接收广播需要权限审查”
- matlab - 使用 buttord() 设计巴特沃斯滤波器时,我得到 N 的零值或负值
- css - 如何处理固定的顶部栏和正文部分具有带光标的输入字段
- asp.net-mvc - 为什么刷新浏览器会触发发布请求而不是获取请求