How to Replace .withOpacity with .withValues in Your Flutter Codebase

Meet DabhiMeet Dabhi
1 min read

In this blog, learn how to automate repetitive code refactoring in your Dart projects using a simple script. Discover how to identify and update .withOpacity method calls to .withValues across your Flutter codebase efficiently, ensuring consistency and saving development time. Perfect for developers looking to streamline their workflow and maintain cleaner code.

import 'dart:io';

void main() {

final directory = Directory('./lib'); // Update path to your project directory

if (!directory.existsSync()) {

print('Error: Directory not found: ${directory.path}');

return; }

final files = directory .listSync(recursive: true) .whereType() .where((file) => file.path.endsWith('.dart'));

for (var file in files) {

String content = file.readAsStringSync();

// Replace .withOpacity(value) with .withValues(alpha: value)

final updatedContent = content.replaceAllMapped( RegExp(r'.withOpacity(([\d.]+))'), (match) => '.withValues(alpha: ${match[1]})', );

file.writeAsStringSync(updatedContent); print('Updated: ${file.path}'); }

print('Replacement complete!');

}

\================

TERMINAL RUN: dart lib/main.dart

4
Subscribe to my newsletter

Read articles from Meet Dabhi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Meet Dabhi
Meet Dabhi

Welcome to Flutter Hub! I'm Meet Dabhi, a Flutter developer with 3+ years of experience in creating beautiful and functional mobile applications (Android, IOS, Web, MacOS, etc.) My journey with Flutter began in 3+, and since then, I've been dedicated to mastering this powerful framework. I created Flutter Hub to share my knowledge, insights, and the latest trends in the Flutter community. Through this blog, I aim to provide valuable resources for both beginners and seasoned developers, helping them navigate the ever-evolving world of Flutter development.