0

I have a single string which contains steps of how to do certain thing. Now I am able to get each step but I am using nested splits so it is getting very long so how can I use loop on it.

code

 Column(
   children: [
               Text(
                    '${asset.lockoutApplicationProcess.split('2.')[0]}',
                               ),
                Text(
                     '2.${asset.lockoutApplicationProcess.split('2.')[1].split('3.')[0]}',
                   ),
               Text(
                     '3.${asset.lockoutApplicationProcess.split('2.')[1].split('3.')[1].split('4.')[0]}',
                      ),
               Text(
                     '4.${asset.lockoutApplicationProcess.split('2.')[1].split('3.')[1].split('4.')[1].split('5.')[0]}',
                       ),
               Text(
                    '5.${asset.lockoutApplicationProcess.split('2.')[1].split('3.')[1].split('4.')[1].split('5.')[1]}',
                                        
                      ),
 ],
 ),
                                  

the string,

"1. Notify affected personnel. 2. Properly shut down machine. 3. Isolate all energy sources. 4. Apply lockout devices, locks, & tags. 5. Verify total de-energization of all sources."

so How can I use loop to reduce the code?

2
  • How does the data in asset.lockoutApplicationProcess look like exactly? Maybe some combination of map and reduce with generator function for Text Widgets.
    – TmKVU
    Jul 30, 2021 at 13:07
  • I have added the string
    – Pokaboom
    Jul 30, 2021 at 13:09

1 Answer 1

2

How about this?

// Collect all the data in an indexed list, skipping the first (empty) element
final splitData = asset.lockoutApplicationProcess.split(RegExp(r"\d\.")).asMap().entries.skip(1);

// Create a Text Widget for each entry, prefixed with the index number 
final textWidgets = splitData.map((entry) => Text("${entry.key}. ${entry.value}"));

// Render the Text widgets in a column
return Column(children: textWidgets.toList());

Note that this will only work for single digits (1-9). If the list could potentially grow beyond 9, you should edit the RegExp to take this into account. For example, the regex RegExp(r"\d+\.") will also catch numbers with more than one digit.

1
  • ok that works like charm thank you for quick solution and mostly the steps won't go beyond 5
    – Pokaboom
    Jul 30, 2021 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.