首页 > 解决方案 > 是否有外部库或简单函数来替换/删除 Flutter(dart) 字符串中的特殊字符

问题描述

应用截图

我如何从 txt 文件中获取数据。

Future<String>? get textAsString async {
  Uri? uri = Uri.tryParse(text.url);
  if (uri != null) {
    String text = await http.read(uri);
    return text;
  }
  return '';
}

我的小部件结构和代码布局。

FutureBuilder<String>(
  future: currentScene.textAsString,
  builder: (context, snapshot) {
    String? text = snapshot.data;
    if (snapshot.hasData && text != null) {
      return ListView(
        padding: kAppPadding,
        controller: _controller,
        children: [
         Text(
           text,
           style: TextStyle(
             height: 1.8,
             fontFamily: 'Roboto',
             color: kWhiteColor,
             fontWeight: FontWeight.w300,
             fontSize: 17,
           ),
         ),
        ],
      );
          } else if (snapshot.hasError) {
            return Center(
              child: AppErrorText(
                onPressed: () {},
              ),
            );
          } else {
            return Center(
              child: AppProgressIndicator(),
            );
          }
        })

我有一个 TXT url 存储在云存储中,我想检索文本并创建一个文本阅读器应用程序。

我使用 http.read(uri) 来获取 TXT 文件的内容并将字符串传递给用 FutureBuilder 包装的文本小部件

我注意到字符串包含一些奇怪的字符(â)......所以我正在寻找一种方法来删除/替换这些字符。

标签: stringflutterhttpdarttxt

解决方案


我不确定外部库,但您可以使用 ASCII 码来识别空间字符。这是空格字符的 ASCII 码

ASCII = 32 to 47 // 32 is a code for blank space
ASCII = 58 to 64 
ASCII = 91 to 96 
ASCII = 123 to 126

在颤振中,您可以获得字符串的 ASCII 值,如下所示

 String _string = 'Hello @World#';
 List<int> asciiList = _string.codeUnits;
 String newString = _string;

 for (int i = 0; i < asciiList.length; i++) {
 if (asciiList[i] >= 33 && asciiList[i] <= 47 ||  //we don't want to remove blank space so we start from 33
     asciiList[i] >= 58 && asciiList[i] <= 64 ||
     asciiList[i] >= 91 && asciiList[i] <= 96 ||
     asciiList[i] >= 123 && asciiList[i] <= 126) {
        newString = newString.replaceAll(_string[i], '');
      } else {
         print("It's not a spacial character");
        }
     }

    print(newString);  //Hello world

推荐阅读