Flutter字符串美化插件pretty_string的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter字符串美化插件pretty_string的使用

Pretty String

style: very good analysis License: MIT

pretty_string 是一个简单的将字符串转换为更易读格式的插件。它特别适用于需要查看复杂对象或长字符串时,使日志输出更加清晰易懂。

安装 💻

pubspec.yaml 文件中添加依赖:

dependencies:
  pretty_string: 1.0.1

然后执行以下命令安装:

flutter pub get

使用方法💯

pretty_string 提供了一个非常简单的方法 .toPrettier(),它可以将任何对象或字符串转换为更美观、更易读的格式。你只需要调用这个方法即可。

示例代码

下面是一个完整的示例,展示了如何使用 pretty_string 来美化复杂的模型对象和普通字符串。

// ignore_for_file: avoid_print

import 'package:pretty_string/pretty_string.dart';

class Device {
  final String id;
  final String platform;
  final String version;
  final bool isRooted;

  const Device({
    required this.id,
    required this.platform,
    required this.version,
    required this.isRooted,
  });

  @override
  String toString() {
    return 'Device(id: $id, platform: $platform, version: $version, isRooted: $isRooted)';
  }
}

class VeryComplicatedModel {
  final int id;
  final String name;
  final String imageUrl;
  final String address;
  final int laptopCount;
  final int age;
  final String parentImageUrl;
  final String wayToGoHome;
  final bool hasChildren;
  final bool hasCamera;
  final bool hasOwnWebsite;
  final Map<String, String> characteristics;
  final String refrigeratorBrand;
  final String carBrand;
  final String status;
  final bool hasGlasses;
  final List<Device> devices;
  final VeryComplicatedModel? friend;

  const VeryComplicatedModel({
    required this.id,
    required this.name,
    required this.imageUrl,
    required this.address,
    required this.laptopCount,
    required this.age,
    required this.parentImageUrl,
    required this.wayToGoHome,
    required this.hasChildren,
    required this.hasCamera,
    required this.hasOwnWebsite,
    required this.characteristics,
    required this.refrigeratorBrand,
    required this.carBrand,
    required this.status,
    required this.hasGlasses,
    required this.devices,
    this.friend,
  });

  @override
  String toString() {
    return 'VeryComplicatedModel(id: $id, name: $name, imageUrl: $imageUrl, address: $address, laptopCount: $laptopCount, age: $age, parentImageUrl: $parentImageUrl, wayToGoHome: $wayToGoHome, hasChildren: $hasChildren, hasCamera: $hasCamera, hasOwnWebsite: $hasOwnWebsite, characteristics: $characteristics, refrigeratorBrand: $refrigeratorBrand, carBrand: $carBrand, status: $status, hasGlasses: $hasGlasses, devices: $devices, friend: $friend)';
  }
}

void main() {
  const instance = VeryComplicatedModel(
    id: 1,
    name: 'Bob',
    imageUrl:
        'https://google.com/ASDFIAJIOWEJFOIAWJFIOSDFOJASFGUOOWUGHAOUWRGHOAWRUGAOWRUGAWORGHOUAWRHGOUAWHOUGaposdkfpoasFAWEOFKP#@(234jiofjas98dfj89@###',
    address:
        'Avenue 100 STREET DUMMY DUMMY DUMMY DUMMY DUMMY DUMMY DUMMY DUMMY ',
    laptopCount: 10,
    age: 53,
    parentImageUrl:
        'https://google.com/ASDFIAJIOWEJFOIAWJFIOSDFOJASFGUOOWUGHAOUWRGHOAWRUGAOWRUGAWORGHOUAWRHGOUAWHOUGaposdkfpoasFAWEOFKP#@(234jiofjas98dfj89@###',
    wayToGoHome:
        'This way Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy',
    hasChildren: true,
    hasCamera: true,
    hasOwnWebsite: false,
    characteristics: {
      'eyes': 'big',
    },
    refrigeratorBrand: 'Samsung',
    carBrand: 'Benz',
    status: 'Very tired',
    hasGlasses: false,
    devices: [
      Device(
        id: 'APOSIFK-fAWFKO123-aSDF',
        platform: 'Android',
        version: '32',
        isRooted: true,
      ),
      Device(
        id: 'APOSIFK-aASODPFKA123!@ODFKAPSOD2@@-@ASDFS',
        platform: 'IOS',
        version: '15.1',
        isRooted: false,
      ),
      Device(
        id: 'aASODPFKA123!@ODFKAPSOD2@@-@ASDFS',
        platform: 'IOS',
        version: '16.1',
        isRooted: false,
      ),
    ],
    friend: null,
  );

  // 打印原始字符串
  print('Original:');
  print(instance);

  // 打印美化后的字符串
  print('\nPrettified:');
  print(instance.toPrettier());
}

输出结果

原始字符串

VeryComplicatedModel(id: 1, name: Bob, imageUrl: https://google.com/ASDFIAJIOWEJFOIAWJFIOSDFOJASFGUOOWUGHAOUWRGHOAWRUGAOWRUGAWORGHOUAWRHGOUAWHOUGaposdkfpoasFAWEOFKP#@(234jiofjas98dfj89@###, address: Avenue 100 STREET DUMMY DUMMY DUMMY DUMMY DUMMY DUMMY DUMMY DUMMY , laptopCount: 10, age: 53, parentImageUrl: https://google.com/ASDFIAJIOWEJFOIAWJFIOSDFOJASFGUOOWUGHAOUWRGHOAWRUGAOWRUGAWORGHOUAWRHGOUAWHOUGaposdkfpoasFAWEOFKP#@(234jiofjas98dfj89@###, wayToGoHome: This way Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy, hasChildren: true, hasCamera: true, hasOwnWebsite: false, characteristics: {eyes: big}, refrigeratorBrand: Samsung, carBrand: Benz, status: Very tired, hasGlasses: false, devices: [Device(id: APOSIFK-fAWFKO123-aSDF, platform: Android, version: 32, isRooted: true), Device(id: APOSIFK-aASODPFKA123!@ODFKAPSOD2@@-@ASDFS, platform: IOS, version: 15.1, isRooted: false), Device(id: aASODPFKA123!@ODFKAPSOD2@@-@ASDFS, platform: IOS, version: 16.1, isRooted: false)], friend: null)

美化后的字符串

VeryComplicatedModel(
  id: 1,
  name: Bob,
  imageUrl: https:///google.com/ASDFIAJIOWEJFOIAWJFIOSDFOJASFGUOOWUGHAOUWRGHOAWRUGAOWRUGAWORGHOUAWRHGOUAWHOUGaposdkfpoasFAWEOFKP#@(
    234jiofjas98dfj89@###,
    address: Avenue 100 STREET DUMMY DUMMY DUMMY DUMMY DUMMY DUMMY DUMMY DUMMY ,
    laptopCount: 10,
    age: 53,
    parentImageUrl: https:///google.com/ASDFIAJIOWEJFOIAWJFIOSDFOJASFGUOOWUGHAOUWRGHOAWRUGAOWRUGAWORGHOUAWRHGOUAWHOUGaposdkfpoasFAWEOFKP#@(
      234jiofjas98dfj89@###,
      wayToGoHome: This way Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy Dummy,
      hasChildren: true,
      hasCamera: true,
      hasOwnWebsite: false,
      characteristics: {
        eyes: big
      },
      refrigeratorBrand: Samsung,
      carBrand: Benz,
      status: Very tired,
      hasGlasses: false,
      devices: [
        Device(
          id: APOSIFK-fAWFKO123-aSDF,
          platform: Android,
          version: 32,
          isRooted: true
        ),
        Device(
          id: APOSIFK-aASODPFKA123!@ODFKAPSOD2@@-@ASDFS,
          platform: IOS,
          version: 15.1,
          isRooted: false
        ),
        Device(
          id: aASODPFKA123!@ODFKAPSOD2@@-@ASDFS,
          platform: IOS,
          version: 16.1,
          isRooted: false
        )
      ],
      friend: null
    )
  )
)

通过对比可以看出,使用 toPrettier() 方法后,输出的字符串更加易读,层次分明,便于调试和理解。

高级用法

你可以自定义 .toPrettier() 的行为,例如更改缩进宽度、分隔符和括号等。以下是默认配置:

String indent = '  ', // 缩进字符,默认为两个空格
List<String> separators = const <String>[','], // 分隔符,默认为逗号
Map<String, String> brackets = const {
  '{': '}',
  '[': ']',
  '(': ')',
}, // 括号匹配,默认为常见的成对括号

如果你需要修改这些配置,可以在调用 .toPrettier() 时传递相应的参数。

贡献 🤖

欢迎提交 Pull Request 来改进这个项目!

运行测试 🧪

要运行所有单元测试,请执行以下命令:

very_good test --coverage

希望这个插件能帮助你在开发过程中更好地处理复杂的对象和字符串!


更多关于Flutter字符串美化插件pretty_string的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter字符串美化插件pretty_string的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用pretty_string插件的一个简单示例。pretty_string插件可以帮助你美化和格式化字符串输出,这在调试或显示日志信息时特别有用。

首先,你需要在你的pubspec.yaml文件中添加pretty_string依赖项:

dependencies:
  flutter:
    sdk: flutter
  pretty_string: ^x.y.z  # 请替换为实际的最新版本号

然后,运行flutter pub get来获取依赖项。

接下来,你可以在你的Flutter应用中使用pretty_string插件。以下是一个完整的示例,展示了如何美化字符串:

import 'package:flutter/material.dart';
import 'package:pretty_string/pretty_string.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pretty String Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Pretty String Demo'),
        ),
        body: Center(
          child: PrettyStringDemo(),
        ),
      ),
    );
  }
}

class PrettyStringDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 原始字符串
    String originalString = "This is a sample string with some numbers 12345 and special characters !@#$%^&*()_+";

    // 使用PrettyString进行美化
    PrettyString prettyString = PrettyString(originalString);

    // 美化后的字符串
    String formattedString = prettyString.beautify();

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Original String:'),
        Text(originalString, style: TextStyle(color: Colors.grey)),
        SizedBox(height: 20),
        Text('Formatted String:'),
        Text(formattedString, style: TextStyle(color: Colors.blue)),
      ],
    );
  }
}

在上面的示例中,我们做了以下几件事:

  1. pubspec.yaml文件中添加了pretty_string依赖项。
  2. MyApp类中创建了一个简单的Flutter应用。
  3. PrettyStringDemo类中定义了一个原始字符串,并使用PrettyString类的beautify方法将其美化。
  4. 使用Text组件在屏幕上显示原始字符串和美化后的字符串。

需要注意的是,pretty_string插件的具体API可能会根据版本有所不同,上述代码中的beautify方法只是示例,实际使用时请参考插件的官方文档或源代码。如果插件提供了更多的配置选项或格式化方法,你也可以根据需要进行调整。

回到顶部