#flutter #dart
#flutter #dart
Вопрос:
Я начинаю изучать 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())));
Ответ №1:
Прямо сейчас вы присваиваете Iterable
значение an int
. Поскольку вам нужна длина, используйте length
свойство Iterable
класса.
int wordscount = regExp.allMatches(myController.text).length;
Это предполагает, что ваше регулярное выражение работает, и мне кажется, что это так. Если это не так, вы можете попробовать это:
[w-]