I have the following list coming from firebase:
[widget.recipeDocument['ingredients'] = 2 eggs, 2 tbsp milk, 30 g flour, 2 tbsp sugar, vanillaextract]
For my list view I split the strings into two parts. Part one is the ingredient amount, with which I do a calculation based on the user's input for the serving size. Part two is the ingredient name. It works for ingredients where I have an amount and an ingredient name. But as you see in my list, I also have "vanillaextract" without an amount. My list view breaks at this point. I am thinking of using RegExpr to detect the ingredient without a space, but I don't know how.
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
primary: false,
itemCount:widget.recipeDocument['ingredients'].length,
itemBuilder: (context, index) {
final ingredient = widget.recipeDocument['ingredients'][index];
RegExp regExp = RegExp(" ");
print('REG EXPR = ${regExp.allMatches(ingredient).length}');
int splitt = ingredient.indexOf(" ");
String measure = ingredient.substring(0,splitt).trim();
String ingredient_name = ingredient.substring(ingredient.indexOf(" ") 1);
double x = double.parse(measure);
double calc = x * _counter;
return Card(
color: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25),
),
child:
ListTile(
dense: true,
visualDensity: VisualDensity(vertical: -3), // to compact
contentPadding: EdgeInsets.only(left: 15.0, right: 15.0),
tileColor: Colors.grey.withOpacity(0.2),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(25),
topRight: Radius.circular(25),
bottomRight: Radius.circular(25),
bottomLeft: Radius.circular(25))),
title:
Text('${(prettify(calc))} ${ingredient_name}',
style: GoogleFonts.nunito(color: Colors.white, fontSize: 18))
)
);
}
),
CodePudding user response:
I would make it like this:
final split = ingredient.split(' ');
double calc = (double.tryParse(split[0]) ?? 0) * _counter;
String ingredient_name = calc == 0 ? ingredient : split.skip(1).join(' ');
Then let the text be
Text('${calc == 0 ? '' : '${prettify(calc)} '}$ingredient_name',
CodePudding user response:
You could use the hasMatch function regExp class to know if the string is matchin your regex :
var list = ["with space", "withoutspace"];
for(var elm in list)
{
var regEx = RegExp(r'\s');
var match = regEx.hasMatch(elm);
print("$elm, has space: $match");
}
result :
with space, has space: true
withoutspace, has space: false
I sugest using "\s" instead of " " as it detect all form of spacing, just to be safe !