Reputation: 43
I'm starting to learn Dart and Flutter and have problem with one app. I'm trying to write an app that counts the number of words in a text string that a user enters. I wrote the countWords function for this, but I don't understand how to properly send a text string to this function. Can someone please explain to me how to do this and correct my code?
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())));
Upvotes: 2
Views: 4897
Reputation: 17133
Right now you're assigning an Iterable
to an int
. Since you want the length, use the length
property of the Iterable
class.
int wordscount = regExp.allMatches(myController.text).length;
This is assuming your regex is working and it appears to me that it is. If it's not then you can try this:
[\w-]+
Upvotes: 2