How to Split Numbers and Letters from a String in Flutter
Working with strings is a common task in mobile app development. In this blog post, we’ll learn how to split numbers and letters from a string using Flutter. We'll use simple UI components and regular expressions (RegExp) to demonstrate the concept in a clean and interactive way.
π± What You’ll Learn:
- How to identify numbers and letters in a string
- How to separate them using Dart logic
- How to display results using Flutter widgets
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Split Numbers and Letters',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Split Numbers and Letters'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String input = "abc123def456";
String numbers = "";
String letters = "";
void _splitString() {
List<String> numList = [];
List<String> letterList = [];
for (int i = 0; i < input.length; i++) {
if (RegExp(r'\d').hasMatch(input[i])) {
numList.add(input[i]);
} else {
letterList.add(input[i]);
}
}
setState(() {
numbers = numList.join();
letters = letterList.join();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Input: $input'),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _splitString,
child: const Text('Split String'),
),
const SizedBox(height: 20),
Text('Numbers: $numbers'),
Text('Letters: $letters'),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _splitString,
tooltip: 'Split',
child: const Icon(Icons.call_split),
),
);
}
}
π§ Explanation:
- Input String: "abc123def456"
- The for loop checks each character:
- If it's a digit (\d), it's added to the numbers list.
- Otherwise, it's added to the letters list.
- Results are joined and displayed in the UI.
✅ Output:
- After tapping the "Split String" button:
Input: abc123def456
Numbers: 123456
Letters: abcdef
π― Use Cases:
- Input validation
- Custom parsers
- Educational apps
- Games or text analysis features
π Final Thoughts:
Flutter makes string manipulation easy with Dart’s powerful RegExp class. You can build intuitive UI and write efficient logic for real-world scenarios like this. Try modifying the input value to experiment with different types of strings.
Want more Flutter tutorials like this? Bookmark this blog or follow us for practical coding tips and examples. π
Tags:
Interview-Prepration