Home > Back-end >  Get Common substring between list and string Flutter
Get Common substring between list and string Flutter

Time:07-18

Sample 1:

tags = ['what','play','school']
string = "what is your name?"

Output = ['what']

Sample 2:

tags = ['what is','play football','school','food']
string = "what is your school name? Do you play football there?"

Output = ['what is','school',"play football"]

How can I achieve this in flutter?

CodePudding user response:

You can use where to find all words present in the string.

void main() {
  List<String> tags = ['what', 'play', 'school'];
  String _string = "what is your name?";

  List<String> commonWords = [...tags.where(_string.contains)];
  print(commonWords); // [what]
}

CodePudding user response:

 import 'package:flutter/material.dart';
 
 class SubStringScreen extends StatefulWidget {
   const SubStringScreen({Key? key}) : super(key: key);
 
   @override
   State<SubStringScreen> createState() => _SubStringScreenState();
 }
 
 class _SubStringScreenState extends State<SubStringScreen> {
   List<String> tags = ['what is', 'play football', 'school', 'food'];
   String dummyText = "what is your school name? Do you play football there?";
   List<String> outputList = [];
 
   @override
   void initState() {
     WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
       for (var element in tags) {
         if (dummyText.contains(element)) {
           outputList.add(element);
         }
       }
       //This will return your result
       print(outputList);
     });
     super.initState();
   }
 
   @override
   Widget build(BuildContext context) {
     return Container(
       color: Colors.white,
       child: Center(
         child: outputList.isNotEmpty
             ? ListView.builder(
                 itemCount: outputList.length,
                 itemBuilder: (BuildContext context, int index) {
                   return Container(
                     padding: const EdgeInsets.all(10.0),
                     child: Text(
                       outputList[index],
                       style: const TextStyle(fontSize: 24, decoration: TextDecoration.none, color: Colors.black),
                     ),
                   );
                 })
             : const Text(
                 "No Result Found",
                 style: TextStyle(fontSize: 24, decoration: TextDecoration.none, color: Colors.black),
               ),
       ),
     );
   }
 }

Output:

enter image description here

enter image description here

CodePudding user response:


void main() {
  var tags = ['what is', 'play football', 'school', 'food'];
  String string = "what is your school name? Do you play football there?";

  print(tags.where((element)=> string.contains(element)));
}

  •  Tags:  
  • dart
  • Related