How to Split String to List Array in Dart/Flutter

In this example, we are going to show you how to split strings into list arrays using delimiters such as space, comma in Dart, or Flutter. Here, we will break or convert a string to an array using whitespace and comma. See the example below:

String str = "Hello This is FlutterCampus";
List<String> strarray = str.split(" ");
//Break string to array with delimiter whitespace "";
print(strarray);
//output: [Hello, This, is, FlutterCampus]

Or, split with a comma:

String countries = "Nepal, India, USA, Russia, UK, China, Canada";
List<String> clist = countries.split(",");
print(clist);
//output: [Nepal,  India,  USA,  Russia,  UK,  China,  Canada]

You can use split() method to break String into List Array in Dart or Flutter. 

List<String> slist =  ["hello", "how", "are", "you"];
String mystr = slist.join("");
print(mystr); //output: hellohowareyou

String mystr1 = slist.join(" ");
print(mystr1); //output: hello how are you

You can also join the list of Strings to one String using the above code. 

import 'package:flutter/material.dart';

Future<void> main() async {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}


class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {

    String str = "Hello This is FlutterCampus";
    List<String> strarray = str.split(" ");
    //Break string to array with delimiter whitespace "";

    return  Scaffold(
          appBar: AppBar( 
              title: Text("Split String to Array"),
              backgroundColor: Colors.redAccent,
          ),
          body: Container( 
            padding: EdgeInsets.all(30),
            child: Column(
              children:strarray.map((word){
                  return Card(
                    child:ListTile(
                        title: Text(word),
                    )
                  );
              }).toList()
            )
          ),
       );
  }
}

Here, we have a string, and it is split into a List array. After breaking the array, we have populated to Column() widget to make it look like a ListView.

In this way, you can split String to List array or convert List Array of Strings to one String in Dart or Flutter. 

No any Comments on this Article


Please Wait...