Flutter 使用总结

Flutter 使用总结

Flutter 安装

  1. 下载:Flutter SDK

    1. 配置环境变量:
      1. 打开终端,打开环境变量配置:open ~/.zshrc

      2. 如果没有.zshrc,就新建:vim ~/.zshrc

      3. 配置环境变量:

        export PATH
        export PATH export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin 
        export PUB_HOSTED_URL=https://pub.flutter-io.cn # 国内用户需要设置
        export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn # 国内用户需要设置
        # export PATH=${PATH}:/flutter的存储地址/flutter/bin:$PATH
        export PATH="$PATH:/xxxflutter的存储地址xxx/bin"
        
        # 最后一行举例:
        # export PATH=${PATH}:/Users/xxx/Documents/code/flutter/bin:$PATH
        # export PATH="$PATH:/Users/xxx/Documents/code/flutter/bin"
        
        # Flutter配置
        #export PATH="$PATH:/Users/andy/Documents/code/flutter/bin"
        #export PATH=/Users/用户名/Documents/flutter/flutter/bin:$PATH
        #export ANDROID_HOME="/Users/用户名/Documents/android_sdk" //android sdk目录,替换为你自己的即可
        #export PATH=${PATH}:${ANDROID_HOME}/tools
        #export PATH=${PATH}:${ANDROID_HOME}/platform-tools
        #export PUB_HOSTED_URL=https://pub.flutter-io.cn
        
      4. 保存并退出编辑::wq

      5. 重新保存一下配置:source ~/.zshrc,来刷新一下,让我们的配置立即生效;

      6. 运行一下看是否配置好:flutter doctor

  2. 下载:Android Studio

    1. Android Studio安装:Flutter插件;打开Android Studio,打开路径:Android Studio->Preferences->Plugins->Marketplace->搜索Flutter,下载Flutter
    2. 安装:Dart插件;(下载Flutter插件,会让先下载Dart插件)
    3. 重启Android Studio让插件生效;
    4. 配置Flutter SDK路径(前提是要先打开一个Flutter项目,才能在Languages & Frameworks下面看到FlutterDart配置入口),就是下载的Flutter SDK的存放路径:打开路径:Android Studio->Preferences->Languages & Frameworks->Flutter->Flutter SDK path,选择下载的Flutter SDK的存放路径;
    5. 配置Dart路径:一般配置好Flutter SDK路径,Dart路径会自动配置,可在路径:Android Studio->Preferences->Languages & Frameworks->Dart->Dart SDK path,查看是否配置成功。
  3. 下载:Xcode

  4. 打开Android Studio的命令行,执行:flutter doctor,使用Flutter的语法进行检测;

Flutter 语法

  1. 命令行

    // 配置检测:首次执行Flutter命令的时候,会自动下载依赖项并自行编译。如果有问题,按照提示,依次解决。
    flutter doctor
    
    // 打包apk
    flutter build apk
    
    // 清空缓存
    flutter clean
    
    // 更新依赖
    flutter pub upgrade
    
    
  2. 解决ListView嵌套ListView不显示和滑动冲突:

    1. 解决方法如下:

      shrinkWrap: true, //为true可以解决子控件必须设置高度的问题
      physics: NeverScrollableScrollPhysics(), //禁用滑动事件
      
    2. 示例代码如下:

      @override
      Widget build(BuildContext context) {
          return Container(
              child: ListView(
                  children: <Widget>[
                      _topSearchView(),
                      _listView(),
                  ],
              ),
          );
      }
      
      Widget _topSearchView(){
          return Container(
              width: ScreenUtil().setWidth(750),
              height: ScreenUtil().setHeight(80),
              padding: EdgeInsets.all(10),
              margin: EdgeInsets.fromLTRB(10, 5, 5, 10),
              decoration: BoxDecoration(
                  color:Colors.white,
                  borderRadius: BorderRadius.circular((10.0)),
                  border: Border.all(
                      width:0.5,color:Colors.black12,
                  )
              ),
              child: Row(
                  children: <Widget>[
                      Icon(Icons.search),
                      Text('搜索')
                  ],
              )
          );
      }
      
      Widget _listView(){
          return Container(
              child: ListView.builder(
                  shrinkWrap: true, //为true可以解决子控件必须设置高度的问题
                  physics:NeverScrollableScrollPhysics(),//禁用滑动事件
                  itemCount: 10,
                  itemBuilder: (context,index){
                      return _item(context,index);
                  },
              ),
          );
      }
      

常见错误

  1. iPhone真机运行,报错:无法打开“iproxy”,因为无法验证开发者,这个问题可能是因为权限不够,执行这句命令就可以搞定:

    sudo xattr -d com.apple.quarantine /Users/zions/development/flutter/bin/cache/artifacts/usbmuxd/iproxy
    
  2. 执行flutter语法报错:command not found: flutter:应该是环境变量配置有问题,重新走一下上面的配置环境变量的步骤。

  3. Android Studio的终端执行flutter doctor报错:

    1. 错误一:

      cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
      

      然后执行:path/to/sdkmanager --install "cmdline-tools;latest"后报错:

      zsh: no such file or directory: path/to/sdkmanager
      

      解决方法:参考错误二;

    2. 错误二:

      Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.`
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
      

      然后执行:flutter doctor --android-licenses后报错:

      Android sdkmanager not found. Update to the latest Android SDK and ensure that the cmdline-tools are installed to resolve this.
      

      解决方法:
      1. 打开SDK Manager -> Appearance & Behavior -> System Setting -> Android SDK -> SDK Tools
      2. 选中Android SDK Command-line Tools (latest)
      3. 点击下方Apply
      4. 进行下载操作;
      5. 下载完成后,点击finish关闭下载页,然后点击Appley应用即可;

    3. 错误三:执行Run报错:

      Error running pod install
      Error launching application on iPhone 13 Pro.
      

      解决方法:
      1. ;

    4. 错误四:执行Run报错:

          ――― TEMPLATE END ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
      
          [!] Oh no, an error occurred.
      
          Search for existing GitHub issues similar to yours:
          https://github.com/CocoaPods/CocoaPods/search?q=dlopen%28%2FLibrary%2FRuby%2FGems%2F2.6.0%2Fgems%2Fffi-1.15.4%2Flib%2Fffi_c.bundle%2C+0x0009%29%3A+tried%3A+%27%2FLibrary%2FRuby%2FGems%2F2.6.0%2Fgems%2Fffi-1.15.4%2Flib%2Fffi_c.bundle%27+%28mach-o+file%2C+but+is+an+incompatible+architecture+%28have+%27arm64%27%2C+need+%27x86_64%27%29%29%2C+%27%2Fusr%2Flib%2Fffi_c.bundle%27+%28no+such+file%29+-+%2FLibrary%2FRuby%2FGems%2F2.6.0%2Fgems%2Fffi-1.15.4%2Flib%2Fffi_c.bundle&type=Issues
      
          If none exists, create a ticket, with the template displayed above, on:
          https://github.com/CocoaPods/CocoaPods/issues/new
      
          Be sure to first read the contributing guide for details on how to properly submit a ticket:
          https://github.com/CocoaPods/CocoaPods/blob/master/CONTRIBUTING.md
      
          Don't forget to anonymize any private data!
      
          Looking for related issues on cocoapods/cocoapods...
      
      Error output from CocoaPods:
      ↳
          Searching for inspections failed: undefined method `map' for nil:NilClass
      
      Error running pod install
      Error launching application on iPhone 13 Pro.
      

      解决方案:可能是因为 M1 芯片的原因:

      1. 执行:sudo arch -x86_64 gem install ffi
      2. 执行:arch -x86_64 pod install; // M1 芯片在 Cocoapods 执行 pod install 下载第三方库前面都需要添加arch -x86_64
    5. 错误五:报错:

      Could not build the application for the simulator.
      Error launching application on iPhone 13 Pro.
      

      解决方案:

      1. 执行:flutter clean,重新运行项目,如果不行试试下一步;

      2. 执行:flutter channel,查看您当前使用的flutter的分支;

        执行结果:

        // 查看当前我的flutter处于stable(稳定)分支
        Flutter channels:
          master
          dev
          beta
        * stable
        
        

        官网上有一句话:我们强烈建议跟踪flutter的stable分支,这是Flutter稳定分支。 如果你需要查看最新的变化,你可以跟踪master分支,但注意这是开发分支,所以稳定性要低得多。

      3. 执行:flutter channel masterflutter channel beta,切换到官方master主分支或beta分支开发即可;

    6. 错误六:更新Flutter版本后报错:

      /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_math_fork-0.3.3/lib/src/widgets/selectable.dart:407:7: Error: The non-abstract class 'InternalSelectableMathState' is missing implementations for these members:
      
      TextSelectionDelegate.copySelection
      TextSelectionDelegate.cutSelection
      TextSelectionDelegate.pasteText
      TextSelectionDelegate.selectAll Try to either
      provide an implementation,
      inherit an implementation from a superclass or mixin,
      mark the class as abstract, or
      provide a 'noSuchMethod' implementation.
      class InternalSelectableMathState extends State ^^^^^^^^^^^^^^^^^^^^^^^^^^^ /C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:985:8: Context: 'TextSelectionDelegate.copySelection' is defined here. void copySelection(SelectionChangedCause cause); ^^^^^^^^^^^^^ /C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:965:8: Context: 'TextSelectionDelegate.cutSelection' is defined here. void cutSelection(SelectionChangedCause cause); ^^^^^^^^^^^^ /C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:973:16: Context: 'TextSelectionDelegate.pasteText' is defined here. Future pasteText(SelectionChangedCause cause); ^^^^^^^^^ /C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:979:8: Context: 'TextSelectionDelegate.selectAll' is defined here. void selectAll(SelectionChangedCause cause); ^^^^^^^^^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_datetime_picker-1.5.1/lib/flutter_datetime_picker.dart:311:32: Warning: Operand of null-aware operation '??' has type 'Color' which excludes null.
      
      'Color' is from 'dart:ui'. color: theme.backgroundColor ?? Colors.white, ^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_neumorphic-3.1.0/lib/src/widget/button.dart:200:14: Error: 'AnimatedScale' is imported from both 'package:flutter/src/widgets/implicit_animations.dart' and 'package:flutter_neumorphic/src/widget/animation/animated_scale.dart'. child: AnimatedScale( ^^^^^^^^^^^^^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_neumorphic-3.1.0/lib/src/widget/switch.dart:167:20: Error: 'AnimatedScale' is imported from both 'package:flutter/src/widgets/implicit_animations.dart' and 'package:flutter_neumorphic/src/widget/animation/animated_scale.dart'. child: AnimatedScale( ^^^^^^^^^^^^^
      
      FAILURE: Build failed with an exception.
      
      * Where:
      Script '/Users/hsh/Documents/code/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 1102
      
      * What went wrong:
      Execution failed for task ':app:compileFlutterBuildDebug'.
      > Process 'command '/Users/hsh/Documents/code/flutter/bin/flutter'' finished with non-zero exit value 1
      
      * 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.
      
      * Get more help at https://help.gradle.org
      
      BUILD FAILED in 29s
      Exception: Gradle task assembleDebug failed with exit code 1
      
      1. 解决方案一:(亲测有效-Andy)

        You need to upgrade your dependencies to fix this issue, so run:
        
        flutter pub upgrade
        
      2. 解决方案二:

        Solution: just add flutter_math_fork: ^0.5.0 to your dependencies in pubspec.yaml to force Flutter to use the newer version of the package.
        
    7. 错误七:定位问题:Android定位没有问题;iOS定位失败,获取不到位置信息:

      解决办法:

      NSLocationUsageDescription
      用于定位使用
      NSLocationAlwaysUsageDescription
      用于始终定位你的当前位置
      NSLocationWhenInUseUsageDescription
      用于定位您的当前位置
      
      最好还要加上-这个必须要加上,不然定位还是会失败
      NSLocationAlwaysAndWhenInUseUsageDescription
      用于定位您的当前位置
      
    8. 错误八:更新flutter,运行报错;

      /Users/kris/Documents/WorkSpace/flutter/.pub-cache/hosted/pub.flutter-io.cn/camera-0.8.1+7/android/src/main/java/io/flutter/plugins/camera/features/resolution/ResolutionFeature.java:135: 警告: [deprecation] CamcorderProfile中的get(int,int)已过时 return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_HIGH); ^ /Users/kris/Documents/WorkSpace/flutter/.pub-cache/hosted/pub.flutter-io.cn/camera-0.8.1+7/android/src/main/java/io/flutter/plugins/camera/features/resolution/ResolutionFeature.java:139: 警告: [deprecation] CamcorderProfile中的get(int,int)已过时 return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_2160P); ^ /Users/kris/Documents/WorkSpace/flutter/.pub-cache/hosted/pub.flutter-io.cn/camera-0.8.1+7/android/src/main/java/io/flutter/plugins/camera/features/resolution/ResolutionFeature.java:143: 警告: [deprecation] CamcorderProfile中的get(int,int)已过时 return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_1080P); ^ /Users/kris/Documents/WorkSpace/flutter/.pub-cache/hosted/pub.flutter-io.cn/camera-
      

      解决办法:

      1. 更新第三方库camera的版本号,在pubspec.yaml里面配置;
      2. 执行flutter pub upgrade更新版本库;
    9. 错误九:更新Flutter报错:CamcorderProfile deprecated in Android API level 31

      解决办法:

      1. 更新compileSdkVersiontargetSdkVersion版本号,路径在android/app/build.gradle
      
      android {
      
      // 重点是要更新这个
      compileSdkVersion 31
      
      sourceSets {
          main.java.srcDirs += 'src/main/kotlin'
      }
      ...
      ...
      ...
      
      
      defaultConfig {
          // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
          applicationId "com.yphsh.nrp.koc"
          minSdkVersion 21
          targetSdkVersion 31
          versionCode flutterVersionCode.toInteger()
          versionName flutterVersionName
          ndk {
              abiFilters 'armeabi', 'armeabi-v7a', 'x86', 'x86_64', 'mips', 'mips64', 'arm64-v8a'
          }
      
      
    10. 错误十:模拟器运行报错:

      Uld: symbol(s) not found for architecture x86_64
      clang: error: linker command failed with exit code 1 (use -v to see invocation)
      note: Using new build system
      note: Planning
      note: Build preparation complete
      note: Building targets in dependency order
      

      解决办法一:

      可能是该静态库不支持在模拟器下编译,可使用真机或Generic iOS Device,一般就不会出现这个错误了;
      

      解决办法二:

      在Build Phases-->Compile Sources(items)中,添加报错的.m文件,点左下角的"+",在弹出框中找到报错的.m文件,选中,add
      

      解决办法三:

      在自制的MYPayBucket.framework中,TARGET--》BuildSetting--》Valid Architectures中添加x86_64;如下图所示。
      具体原因,真机arm格式,模拟器x87格式,所以MYPayBucket.framework不支持。添加x86_64格式就行。
      
11. 错误十一: `Android Studio`升级后,执行`flutter doctor`报错:

```
Doctor summary (to see all details, run flutter doctor -v):
The operation couldn’t be completed. Unable to locate a Java Runtime.
Please visit http://www.java.com for information on installing Java.
The operation couldn’t be completed. Unable to locate a Java Runtime.
Please visit http://www.java.com for information on installing Java.
[✓] Flutter (Channel stable, 2.10.2, on macOS 13.2.1 22D68 darwin-arm, locale zh-Hans-MY)
[!] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    ✗ Could not determine java version
[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
[✓] Chrome - develop for the web
[!] Android Studio (version 2022.1)
    ✗ Unable to find bundled Java version.
[✓] IntelliJ IDEA Ultimate Edition (version 2022.2.2)
[✓] VS Code (version 1.75.1)
[✓] Connected device (1 available)
[!] HTTP Host Availability
    ✗ HTTP host https://maven.google.com/ is not reachable. Reason: An error occurred while checking the HTTP host: Operation timed out

! Doctor found issues in 3 categories.

```

解决办法一:

1. 在`应用程序`中找到`Android Studio`;
2. 右键,选择`显示包内容`;
3. 打开`Contents`;
4. 新建`jre`文件夹;
5. 复制`jar`文件夹下的`Contents`文件夹到新建的`jre`文件夹;


解决方法二:建一个软链

1. 打开终端;
2. 执行:`ln -s /Applications/Android\ Studio.app/Contents/jbr /Applications/Android\ Studio.app/Contents/jre`
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,793评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,567评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,342评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,825评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,814评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,680评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,033评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,687评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,175评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,668评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,775评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,419评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,020评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,206评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,092评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,510评论 2 343

推荐阅读更多精彩内容