You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中replaceAll/replaceFirst方法不生效问题求助

Dart字符串替换不生效的问题解决

你的代码问题核心在于Dart的String是不可变类型:replaceAll、replaceFirst这类字符串替换方法不会修改原字符串,而是返回一个全新的替换后的字符串。你现在只是链式调用了这些方法,但没有把返回的新字符串重新赋值给uri变量,所以最后返回的还是最初定义的未替换字符串。

另外还有个小细节错误:最后一个替换的占位符你写的是destination,漏了前后的大括号{},这会导致目的地参数无法被正确替换。

修正后的代码如下:

static String generateUri(Trip trip, String leading){
  String uri = "{leading}://trips?time={time}&origin={origin}&destination={destination}";
  // 将替换后的新字符串重新赋值给uri变量
  uri = uri.replaceAll("{leading}", leading)
      .replaceAll("{time}", trip.departurePlannedTime!.toIso8601String())
      .replaceAll("{origin}", trip.originLocation!.id.toString())
      .replaceAll("{destination}", trip.destinationLocation!.id.toString());
  return uri;
}

内容的提问来源于stack exchange,提问作者Maritn Ge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:03:43