futter开发错误积累

news/2025/2/6 0:06:12/

注:后面添加以倒序方式添加

24.高帧率手机上,flutter列表慢慢拖动的时候会感觉到明显的抖动现象

比如,一加手机输入的运行频率为120hz,而显示屏的运行频率为90hz。滚动时,这种不匹配会导致性能下降,google团队通过以下的方法来解决此问题。

void main() {GestureBinding.instance.resamplingEnabled = true;run(MyApp());
}

23.列表向右滚动到最后或向左滚动到最开始时错误信息: 'package:flutter/src/widgets/overscroll_indicator.dart': Failed assertion:ine 243 pos 14: 'notification.metrics.axis == widget.axis': is not true

修改前代码:

Scrollable(axisDirection: AxisDirection.down,viewportBuilder: (context, offset) {return CustomScrollView(scrollDirection: Axis.horizontal,slivers: [SliverFixedExtentList(itemExtent: 100,delegate: SliverChildBuilderDelegate((context, column) => ListTile(title: Text('ddfds$column'),),childCount: 10,),)]);},);

修改后代码:

Scrollable(axisDirection: AxisDirection.down,viewportBuilder: (context, offset) {return NotificationListener<OverscrollNotification>(// Suppress OverscrollNotification events that escape from the inner scrollableonNotification: (notification) =>notification.metrics.axisDirection != AxisDirection.down,child: CustomScrollView(scrollDirection: Axis.horizontal,slivers: [SliverFixedExtentList(itemExtent: 100,delegate: SliverChildBuilderDelegate((context, column) => ListTile(title: Text('ddfds$column'),),childCount: 10,),)]),);},);

22.flutter版本升级后,运行报错

版本升级之后,爆了一堆莫名其妙的错误

解决办法:

1,删除项目中.idea文件夹,build文件夹,pubspec-lock文件
2,运行命令 flutter pub get

21.Could not create task ':shared_preferences_android:generateDebugUnitTestConfig'.
this and base files have different roots:

G:\loansuper\loansuper\build\shared_preferences_android and C:\Users\*****\AppData\Local\Pub\Cache\hosted\pub.flutter-io.cn\shared_preferences_android-2.0.12\android.

解决:找到c盘缓存文件删除

20.Text文字下方出现黄色双下划线

原因:在Flutter中,Text组件是属于Material风格的,这就要求我们的根组件最好也是Material风格的,否则UI展示可能会有一些问题。刚刚提到的启动页,根组件直接使用的层叠布局Stack,而Stack就不属于Material风格,当Stack内部嵌套Text的时候就会出现文字下方带有两条黄色下划线的现象。

解决方法

这个问题主要有两种方式解决:
1.修改根节点的组件类型为Scaffold或者Material

Scaffold(body: content,);Material(child: content);

2.针对出现问题的Text组件,修改其style下的decoration属性为TextDecoration.none

child: Text("WENT",style:TextStyle(color: Colors.white, decoration: TextDecoration.none),),

19.Building with plugins requires symlink support.Please enable Developer Mode in your system settings

原因:要开启windows开发者模式

解决:进入电脑中的设置页面,找到开发者选项,打开开发者模式

18.Flutter版本升级到2.10.4后出现的问题

   1.Android Gradle plugin requires Java 11 问题解决

AGP 7.0.0-alpha02起需要使用Java 11
https://developers-jp.googleblog.com/2020/12/announcing-android-gradle-plugin.html

当Java版本不正确时,Gradle的sync阶段回报错如下:

需要注意gradle的Java版本并非AndroidStudio工程依赖的Java版本。 

以Mac版本为例:AndroidStudio > Preferences... > Gradle

 2.编译失败:Execution failed for task ':app:processDebugMainManifest'.(`android:exported`相关)

Execution failed for task ':app:processDebugMainManifest'.
> Manifest merger failed : android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

解决:根据错误提示,targetSdkVersion大于等于SDK 21(也就是Android 12)时,如果有的Activity配置了Intent-filter,必须也同时配置exported属性,否则编译失败。

将Manifest中有配置Intent-filter的Activity加上android:exported属性

        <activityandroid:name=".MainActivity"android:exported="true"android:label="@string/app_name"android:launchMode="standard"android:screenOrientation="portrait"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity>

17.Flutter之Swiper:疯狂滚动bug

解决方案1:autoplay 设置为false,loop 也设置为false 就好了 需要自动轮播 用swiperController在生命周期里控制自动播放就行

解决方案2:给Swiper指定index之后 初始化时就不会乱滚了

16.解决TextOverflow.ellipsis显示不出三点

Text想要展示一行,显示不下展示省略号,通常使用overflow: TextOverflow.ellipsis,
缺陷: 会将长字母或者数字串整体显示省略
例子: 分组YD-YXTJA-2102217-001113123123123123123,可能会显示成:分组YD-…

解决方案:将每个字符串之间插入零宽空格

String breakWord(String word) {if (word == null || word.isEmpty) {return word;}String breakWord = ' ';word.runes.forEach((element) {breakWord += String.fromCharCode(element);breakWord += '\u200B';});return breakWord;}

调用

Text(breakWord("YD-YXTJA-2102217-001113123123123123123"),maxLines: 1,overflow: TextOverflow.ellipsis,)



 

15.多个可滑动控件嵌套后,在滑动时报错:

Another exception was thrown: The provided ScrollController is currently attached to more than one ScrollPosition.

解决: 给用到滚动的组件都建一个 controller, 就好了,如:

late ScrollController _pageScrollerController;@overridevoid initState() {super.initState();_pageScrollerController = ScrollController();realTimeBloc = RealTimeBloc();}@overridevoid dispose() {realTimeBloc.close();_pageScrollerController .dispose();super.dispose();}ListView.builder(controller: _pageScrollerController ,shrinkWrap: true, //范围内进行包裹(内容多高ListView就多高)physics: NeverScrollableScrollPhysics(),itemCount: state.rechargemodel?.rechargeInfo?.length,itemBuilder: (context, index) {return _tableRechargeRowData(state.rechargemodel?.rechargeInfo?[index]);},),

14.Flutter asset文件被压缩的问题

背景:严格来说,这不是Flutter范畴问题,但是确实是我在写Flutter插件时遇到的,实际上是一个Android问题,以此文做一个小小的备忘。最近在更新Fluwx[1],正好对分享文件的功能进行重构,然后需要对该功能进行测试,然后在Android上会抛个异常:

java.io.FileNotFoundException: This file can not be opened as a file descriptor; it is probably compressed

然而我并没有压缩啊,以前分享asset图片明明没问题啊!!!

重现:先看看我们是怎么引入的文件,在pubspec.yaml中如下:

assets:- assets/doc/fluwx.docx

讲道理,在iOS上可以正常分享,这基本可以断定不是Flutter本身引起的问题。这就奇怪了,同样的方式引入图片都不会出现这样的问题,怎么我引入word就会有这样的问题?

分析:首先,我们要知道Flutter会打把assets下的文件打包到Android中的assets中,具体为app/assets/flutter_assets/。到这里,问题已经有眉目了。在apk打包过程中,aapt会选择性地对assets下的文件进行压缩。下面摘抄的Package.cpp的代码揭示了哪些格式的文件默认不会被压缩:

/* these formats are already compressed, or don't compress well */
static const char* kNoCompressExt[] = {".jpg", ".jpeg", ".png", ".gif",".wav", ".mp2", ".mp3", ".ogg", ".aac",".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet",".rtttl", ".imy", ".xmf", ".mp4", ".m4a",".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2",".amr", ".awb", ".wma", ".wmv"
};

解决:知道原因就很好解决了, 告诉aapt不要压缩他。在你的Gradle文件(android/app/build.gradle)中添加如下代码:

android {aaptOptions {noCompress "docx"}
}

引用:Fluwx: https://github.com/OpenFlutter/fluwx

13.Error connecting to the service protocol: failed to connect

地址:https://juejin.im/post/6857775588762091533

12.dio或http请求阻塞ui,导致页面UI卡顿问题及其解决办法

地址:https://juejin.im/post/6844904158735106061

11. 解决Flutter的ListView嵌套ListView滑动冲突以及无限高度问题:

shrinkWrap: true, //解决无限高度问题
physics:NeverScrollableScrollPhysics(),//禁用滑动事件

可滑动控件都有这两个属性,给子滑动部件设置上这两个参数,即可办到子ListView跟随父ListView滑动

10.Flutter 添加新插件后报The number of method references in a .dex file cannot exceed 64K.

地址:https://juejin.im/post/684490404803485696

9.弹窗键盘弹起影响布局解决方案地址:https://juejin.im/post/6844904048898867208

8.TextField相关的问题

  1.Flutter的输入框TextField在调用controller.clear()方法后不调用onChanged()方法

源码:
void clear() {value = const TextEditingValue(selection: TextSelection.collapsed(offset: 0));
}

解决:再调用clear()方法后手动调用onChanged方法

如:

  onTap: () {widget.controller.clear();widget.onChanged('');}

     2.字数统计异常

一般情况下,实现字数统计方法如下:

TextField(onChanged: (value){setState(() {_textFieldValue = value;});},decoration: InputDecoration(counterText: '${_textFieldValue.length}/32'),
),

大部分情况下是没有问题的,但是在 IOS 简体拼音输入法下有问题(可能其他输入法也有类似的问题),效果如下:

中文输入法统计正在编辑中文的过程中会统计英文,假如限制5个中文,当输入4个中文后,最后一个中文输入2个及以上英文时,会触发最大字数限制,这当然不是我们想要的效果。

下面说下如何修复这个问题,关键是 TextField 中 「controller.value.composing」 这个属性,官方文档说明:The range of text that is still being composed.仍在编写的文本范围。

就是上面GIF中出现下划线的部分,字数统计计算:

  TextEditingController _controller = TextEditingController();int _wordLength = 0;/// 计算字数,不算正在编辑的文字void _computeWordCount() {var valueLength = _controller.value.text.length;var composingLength =_controller.value.composing.end - _controller.value.composing.start;setState(() {_wordLength = valueLength - composingLength;});}
TextField(controller: _controller,onChanged: (value){_computeWordCount();},decoration: InputDecoration(counterText: '$_wordLength/32'),
),

 3.文字无法居中

(注:目前方法1暂时可以居中)

解决方法1:

 decoration: InputDecoration(isCollapsed: true,border: InputBorder.none,
)

解决方法2:

 decoration: InputDecoration(contentPadding: EdgeInsets.zero,border: OutlineInputBorder(borderSide: BorderSide.none),
)

解决方法3:

设置contentPadding,它需要设置的值是根据 TextField的高度 和 文字高度共同决定的,公式是:( TextField的高度 - 文字高度)/2

我们需要计算出文字的高度:

///value: 文本内容;fontSize : 文字的大小;fontWeight:文字权重;maxWidth:文本框的最大宽度;maxLines:文本支持最大多少行 ;locale:当前手机语言;textScaleFactor:手机系统可以设置字体大小(默认1.0)static double calculateTextHeight(fontSize,{String value = '',FontWeight fontWeight,double maxWidth = double.infinity,int maxLines = 1,double textScaleFactor = 1.0 //字体缩放大小}) {TextPainter painter = TextPainter(///AUTO:华为手机如果不指定locale的时候,该方法算出来的文字高度是比系统计算偏小的。locale: WidgetsBinding.instance.window.locale,maxLines: maxLines,textDirection: TextDirection.ltr,textScaleFactor: textScaleFactor,text: TextSpan(text: value,style: TextStyle(fontWeight: fontWeight,fontSize: fontSize,)));painter.layout(maxWidth: maxWidth);///文字的宽度:painter.widthreturn painter.height;}

设置 contentPadding:

///(textfield高度 - 文字高度 / 2)
contentPadding: EdgeInsets.symmetric(horizontal: 12,vertical: ( TextField的高度 - 文字高度)/2,

4.如何优雅地修改 TextField 的高度。只要轻轻地在 InputDecoration中,加入一个 constraints 约束即可

TextField(decoration: InputDecoration(constraints: BoxConstraints(maxHeight: 35),//略...

添加之前:

添加之后:

原理相关参考:Flutter 布局探索 | 如何分析尺寸和约束

1.错误信息:Flutter中解决ListView没配合AppBar使用顶部出现空白间隔

ListView头部有一段空白区域,是因为当ListView没有和AppBar一起使用时,头部会有一个padding,为了去掉padding,可以使用MediaQuery.removePadding

Widget _listView(BuildContext context){return MediaQuery.removePadding(removeTop: true,context: context,child: ListView.builder(itemCount: 10,itemBuilder: (context,index){return _item(context,index);},),);}

2.错误信息:A RenderFlex overflowed by 75497372 pixels on the right.

控件超出了屏幕尺寸。表现为应用并没有闪退,只是UI显示会与预期不符


3.错误信息:Incorrect use of ParentDataWidget.

解决方案:
####### 问题:
经过排查后发现是Expanded、Flexible等组件,在“Container、Padding、Stack”组件中导致的。
####### 方案:
保持:Expanded、Flexible只在Row、Column等组件内,不在其他组件内使用。

4.错误信息:iPhone 升级iOS14.2后,通过Android Studio运行Flutter项目,安装Flutter App至iPhone。断开iPhone与Android Studio链接或停止运行后,再次打开Flutter App,App页面提示:

In iOS 14+, debug mode Flutter apps can only be launched from Flutter tooling, IDEs with Flutter plugins
or from Xcode.Alternatively, build in profile or release modes to enable launching from the home screen.译文:在iOS 14+中,调试模式的Flutter应用只能从Flutter工具中启动,如具有Flutter插件的IDE(Android Studio、VSCode) 或使用Xcode。 或者,构建时使用配置文件或发布模式以便使apps能够从主屏幕启动。

手机截图:

解决方案:

使用flutter的release模式,终端输入:flutter run --release

5.warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versionsis 9.0 to 14.4.99. (in target 'BMKLocationKit' from project 'Pods')

解决podfile文件中添加:

参考:Automatically assigning platform `iOS` with version `8.0` on target `Runner`_Fighting宁的博客-CSDN博客

# Uncomment this line to define a global platform for your project
platform :ios, '9.0'post_install do |installer|installer.pods_project.targets.each do |target|target.build_configurations.each do |config|config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '9.0'endend
end

6.flutter升级到2.0后报错如下信息:

参考:Flutter 升级 2.0 填坑指导,带你原地起飞_CSDN资讯-CSDN博客

  1.shadowThemeOnly相关

../../../../../Downloads/flutter/.pub-cache/git/flutter-cupertino-date-picker-eb3a837589e0477b2cb99dad03e9e4fb69fb6dde/lib/src/date_picker.dart:103:34: Error: No named parameter with the name 'shadowThemeOnly'.theme: Theme.of(context, shadowThemeOnly: true),                ^^^^^^^^^^^^^^^                        
../../../../../Downloads/flutter/packages/flutter/lib/src/material/theme.dart:107:20: Context: Found this candidate, but the arguments don't match.static ThemeData of(BuildContext context) { 

原因:新版 flutter shadowThemeOnly 主题被移除

解决:注释掉flutter_cupertino_date_picker第三方包调用 shadowThemeOnly 的代码

2.resizeToAvoidBottomPadding被删除,用resizeToAvoidBottomInset代替

7.setState() or markNeedsBuild() called during build.

原因是 组件还没有构建完毕,就要更新数据,所以:

解决方法1.在进行加载一页面时延时加载:

 Future.delayed(Duration(milliseconds: 200)).then((e) {setState(() {list.add("1");});});

推荐解决方法2:通过addPostFrameCallback可以做一些安全的操作,在有些时候是很有用的,它会在当前Frame绘制完后进行回调,并只会回调一次,如果要再次监听需要再设置
 WidgetsBinding.instance.addPostFrameCallback((callback) {undefined
      initData();
    });
 

参考:http://t.csdn.cn/shcOi


http://www.ppmy.cn/news/734169.html

相关文章

ABAP学习(8):操作EXCEL

ABAP操作EXCEL 1、EXCEL导入内表 方式1: 调用function,’F4_FILENAME’获取文件名。通过屏幕元素Prameter的帮助事件&#xff0c;弹出文件选择框&#xff0c;获取选择文件名。 调用function,’TEXT_CONVERT_XLS_TO_SAP’&#xff0c;将选择excel数据放入内表。 示例&#xff1a…

【7月新刊】避雷!这4本期刊竟无影响因子?!7月期刊目录已更新 (多本期刊影响因子上涨)~

6月28日&#xff0c;科睿唯安发布了最新JCR报告&#xff0c;一时间几家欢喜几家愁&#xff0c;但有的作者却发现&#xff0c;自己投稿的期刊虽然被核心库收录却没有影响因子&#xff0c;不免慌了神。 总的来说&#xff0c;被核心库收录的期刊没有公布影响因子&#xff0c;一般…

华为手机NFC模拟加密的门禁卡详细教程

目标&#xff1a;将门禁卡、考勤卡、会员卡、停车卡、电梯卡等等各种卡模拟进手机里&#xff0c;模拟后可用手机代替刷卡&#xff0c;无需root&#xff0c;不用电脑 背景介绍&#xff1a; 1、前言   目前&#xff0c;IC卡已被广泛应用于身份识别、金融消费、安全认证等领域。…

ID卡拆解做成手机刷门禁(类似NFC功能)

小区门禁是ID卡,频率是125K 手机NFC功能是只能刷IC卡13.56M的,所以要想手机刷iD卡就得自己动手补装了 准备材料: 手机防磁贴和线圈 (你可以直接购买线圈,但是要复制卡号到你线圈里面,需要复制器,我这里没有买复制器,于是把蓝色钥匙扣给拆了) 不多说,直接上图 新买回来的样子…

android添加nfc门禁卡,IOS14nfc怎么添加门禁卡?NFC门禁卡教程[多图]

IOS14nfc怎么用&#xff1f;IOS14NFC开关在哪&#xff1f;NFC功能推出后安卓各种机型都可以使用了&#xff0c;苹果直到IOS14才可以用&#xff0c;好多果粉看到这个消息后非常的开心。哪么这个功能在哪里开启呢&#xff1f;还不知道的苹果用户千万不要错过了这个NPC教程哟。 IO…

NFC读卡功能简单使用介绍

manifest配置&#xff1a;权限配置&#xff0c;nfc要求&#xff0c;最小sdk 您的应用支持的最低 SDK 版本。API 级别 9 仅通过 ACTION_TAG_DISCOVERED 支持有限的标签调度&#xff0c;并且只能通过 EXTRA_NDEF_MESSAGES extra 提供对 NDEF 消息的访问权限。无法访问其他任何标签…

NFC入门介绍

缩写词 NFCNear Field Communication近场通信OEMOriginal Equipment Manufacturer原始设备制造商HWHardware硬件OMAPIOpen Mobile Application Programming Interface开发移动应用程序编程接口eSEEmbedded Secure Element嵌入式安全元件SEMSSecure Element Management Service…

Android NFC识别CPU卡和m1卡

博客导航 基础知识 tag dispatch系统定义了三种intent&#xff1a;ACTION_NDEF_DISCOVERED、ACTION_TECH_DISCOVERED、ACTION_TAG_DISCOVERED。它们的优先级优先级分由高到低。对于要识别的CPU卡和m1卡来说&#xff0c;要过滤的是ACTION_TECH_DISCOVERED。 支持的tag技术 Cla…