在整个API响应字符串中,我想在Flutter中只获取特定的单词,如何做到?

huangapple go评论71阅读模式
英文:

Among the whole API response string I wants to get only particular word in flutter how to do it?

问题

这是获取图像路径的响应,文件可以是pdf、jpeg或其他格式。对于图像,我将在对话框中显示它,对于pdf,我需要将其下载到用户的设备。为此,首先我需要检查文件是否为pdf,为此我希望从整个路径中获取文件格式的扩展名,例如pdf或jpeg(在第0个和第1个位置显示)。如何使用字符串分割来实现这一点?我尝试了几种方法,但无法获得结果。请指导我如何实现。

以下是我尝试拆分并获取文件格式的代码:

List<String> imgfiles = [];
@override
void initState() {
  init();
  super.initState();
}

Future<void> init() async {
  dynamic companyId = getIt<SharedPreferences>().getString('companyId');

  //final docs = DioClient().KycDetails(companyId);
  dynamic responseData = await getIt<DioClient>().KycDetails(companyId);
  final details = responseData['data'];
  Aadhar Docdetails = Aadhar.fromJson(details['aadhar']);
  setState(() {
    List<String> imgfiles = Docdetails.files;
    this.imgfiles = imgfiles;
  });
}

Padding(
  padding: EdgeInsets.only(
    left: w1p * 3,
    right: w1p * 6,
  ),
  child: SizedBox(
    width: maxWidth,
    height: 50,
    child: ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: imgfiles.length,
      itemBuilder: (context, index) {
        String doc = imgfiles[index];
        print('整个文件路径 >>>>>>$doc');

        String doc1 = doc.split('jpeg').toString();
        print('doc1.>>>>>$doc1');

        return GestureDetector(
          onTap: () {
            showDialog(
              context: context,
              builder: (context) {
                return Dialog(
                  child: Container(
                    width: 220,
                    height: 200,
                    child: Image.network(
                      '$doc',
                      fit: BoxFit.cover,
                    ),
                  ),
                );
              },
            );
          },
          child: imageDialog(),
        );
      },
    ),
    //_checkController();
  ),
),

在上面的代码中,您尝试使用.split()方法来获取文件格式,但是.split()方法不会返回文件扩展名。您可以尝试使用path库来提取文件扩展名,例如:

import 'package:path/path.dart' as path;

// ...

String doc1 = path.extension(doc); // 这将返回文件的扩展名,例如'.jpeg' 或 '.pdf'

然后,您可以使用doc1来确定文件的类型(pdf或jpeg)并采取相应的操作。

英文:

Below is the response where I am getting image path.the file can be pdf or jpeg or any other format. for image i am showing it in dialogue and for pdf I have to download it to the user's device.For that first I have to check where the file is pdf or not for that i wants to get the extension of file format like pdf or jpeg from whole path (shown in 0th and 1st). How to do it using spilt string I have tried several ways but unable to get the result.Please guide me regarding it.

0:&quot;https://xuriti-prod-kyc.s3.ap-south-1.amazonaws.com/27AAACB2100P1ZX/1675230131954-download-%281%29.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAXALYDECMNE2HOZS7%2F20230216%2Fap-south-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20230216T063528Z&amp;X-Amz-Expires=900&amp;X-Amz-Signature=59204e81b56cd325de1531a1e6c6a67c5030c76c0516b4719e40986e1ef1d917&amp;X-Amz-SignedHeaders=host&quot;

1:&quot;https://xuriti-prod-kyc.s3.ap-south-1.amazonaws.com/27AAACB2100P1ZX/1675230131972-download.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAXALYDECMNE2HOZS7%2F20230216%2Fap-south-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20230216T063528Z&amp;X-Amz-Expires=900&amp;X-Amz-Signature=867311e96282f231406f46d5f2a5d11befe985b0b3a0ab161f69dfb3465b50a9&amp;X-Amz-SignedHeaders=host&quot;

Below is my code where i tried to split and get the file format:

List imgfiles = [];
  @override
  void initState() {
    init();
    super.initState();
  }

  Future init() async {
    dynamic companyId = getIt&lt;SharedPreferences&gt;().getString(&#39;companyId&#39;);

    //final docs = DioClient().KycDetails(companyId);
    dynamic responseData = await getIt&lt;DioClient&gt;().KycDetails(companyId);
    final details = responseData[&#39;data&#39;];
    Aadhar Docdetails = Aadhar.fromJson(details[&#39;aadhar&#39;]);
    setState(() {
      List&lt;String&gt; imgfiles = Docdetails.files;
      this.imgfiles = imgfiles;
    });
  }
  Padding(
                padding: EdgeInsets.only(
                  left: w1p * 3,
                  right: w1p * 6,
                ),
                child: SizedBox(
                  width: maxWidth,
                  height: 50,
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: imgfiles.length,
                    itemBuilder: (context, index) {
                      String doc = imgfiles[index];
                    print(&#39;the whole filepath  &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;$doc&#39;);

                    String doc1 = doc.split(&#39;jpeg&#39;).toString();
                    print(&#39;doc1.&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;$doc1&#39;);

                      

                      return GestureDetector(
                          onTap: () {
                            showDialog(
                                context: context,
                                builder: (context) {
                                  return Dialog(
                                    child: Container(
                                      width: 220,
                                      height: 200,
                                      child: Image.network(
                                        &#39;$doc&#39;,
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                  );
                                });
                          },
                          child: imageDialog());
                    },
                  ),
                  //_checkController();
                ),
              ),

答案1

得分: 1

只需使用split和substring

String getExtension(url) {
  url = url.split('?')[0];
  url = url.split('/').last;
  return url.contains('.') ? url.substring(url.lastIndexOf('.') + 1) : "";
}

用法,

const url =
    "https://xuriti-prod-kyc.s3.ap-south-1.amazonaws.com/27AAACB2100P1ZX/1675230131954-download-%281%29.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAXALYDECMNE2HOZS7%2F20230216%2Fap-south-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20230216T063528Z&amp;X-Amz-Expires=900&amp;X-Amz-Signature=59204e81b56cd325de1531a1e6c6a67c5030c76c0516b4719e40986e1ef1d917&amp;X-Amz-SignedHeaders=host";

final extension = getExtension(url); // 返回 'jpeg'

if (extension == "jpeg") {
    // 显示图像
} else if (extension == "pdf") {
    // 显示下载选项
}
英文:

just use split and substring

String getExtension(url){
  url = url.split(&#39;?&#39;)[0];
  url = url.split(&#39;/&#39;).last;
  return url.contains(&#39;.&#39;) ? url.substring(url.lastIndexOf(&#39;.&#39;)+1) : &quot;&quot;;
}

Usage,

 const url = 
   &quot;https://xuriti-prod-kyc.s3.ap-south-1.amazonaws.com/27AAACB2100P1ZX/1675230131954-download-%281%29.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAXALYDECMNE2HOZS7%2F20230216%2Fap-south-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20230216T063528Z&amp;X-Amz-Expires=900&amp;X-Amz-Signature=59204e81b56cd325de1531a1e6c6a67c5030c76c0516b4719e40986e1ef1d917&amp;X-Amz-SignedHeaders=host&quot;;

final extension = getExtension(url); // return &#39;jpeg&#39;

if (extension == &quot;jpeg&quot;){
    // show image
}
else if(extension == &quot;pdf&quot;) {
    // show download option
}

答案2

得分: 0

以下是翻译好的部分:

如果您确信响应将具有一致的格式您可以尝试以下方法此外为了确保您可以在每个步骤上添加一些检查以避免异常

final String input = 'https://xuriti-prod-kyc.s3.ap-south-1.amazonaws.com/27AAACB2100P1ZX/1675230131972-download.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAXALYDECMNE2HOZS7%2F20230216%2Fap-south-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20230216T063528Z&amp;X-Amz-Expires=900&amp;X-Amz-Signature=867311e96282f231406f46d5f2a5d11befe985b0b3a0ab161f69dfb3465b50a9&amp;X-Amz-SignedHeaders=host';

final res = input.split('/').last.split('?').first.split('.').last;
英文:

If you are sure response will have consistent format you can try this. Also to be sure you may add a couple of checks on each step to avoid exceptions.

final String input = &#39;https://xuriti-prod-kyc.s3.ap-south-1.amazonaws.com/27AAACB2100P1ZX/1675230131972-download.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAXALYDECMNE2HOZS7%2F20230216%2Fap-south-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20230216T063528Z&amp;X-Amz-Expires=900&amp;X-Amz-Signature=867311e96282f231406f46d5f2a5d11befe985b0b3a0ab161f69dfb3465b50a9&amp;X-Amz-SignedHeaders=host&#39;;

final res = input.split(&#39;/&#39;).last.split(&#39;?&#39;).first.split(&#39;.&#39;).last;

答案3

得分: 0

这里可以使用正则表达式而不是拆分:

String getExtension(url){
  final regexJpeg = RegExp(r'\.jpeg\?*');
  final regexPdf = RegExp(r'\.pdf\?*');
  if(regexJpeg.hasMatch(url)){
    return 'jpeg';
  }
  else if(regexPdf.hasMatch(url)){
    return 'pdf';
  } else{
    return 'unknown';
  }
}
英文:

Instead of splitting you can use regex here:

String getExtension(url){
  final regexJpeg = RegExp(r&#39;\.jpeg\?*&#39;);
  final regexPdf = RegExp(r&#39;\.pdf\?*&#39;);
  if(regexJpeg.hasMatch(url)){
    return &#39;jpeg&#39;;
  }
  else if(regexPdf.hasMatch(url)){
    return &#39;pdf&#39;;
  } else{
    return &#39;unknown&#39;;
  }
}

</details>



huangapple
  • 本文由 发表于 2023年2月16日 15:47:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469201.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定