Flutter初体验
Flutter初体验 · April 7, 2019 views: 108
1. 准备工作
安装Android Studio,并下载sdk,安装插件Flutter
安装Flutter
export PUB_HOSTED_URL=https://pub.flutter-io.cn export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn git clone -b dev https://github.com/flutter/flutter.git
把flutter的bin目录放到环境变量PATH中去(方法很多,/etc/profile , ~/.profile, ~/.bash_profile等文件可以修改)
设置futter
#配置Android Studio目录 flutter config --android-studio-dir Android Studio安装目录 #配置Android Sdk目录 flutter config --android-sdk Android SDK目录
检查
flutter doctor --android-licenses flutter doctor
2. 开始工作
创建项目时遇到了问题,用AS创建Flutter项目时总是假死,后来网上找的解决方法是用命令行创建。
flutter create myapp
首先按张官方教程写了一个简单页面
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hellow Flutter',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: new Scaffold(
appBar: new AppBar(
title: new Text('Welcome to Flutter'),
),
body: new Center(
child: new Text('Hello World'),
),
),
);
}
}
连接到手机运行无误。
然后增加点难度,用上了 image_picker 这个插件,实现一个相册功能,手机上运行总是出错。
手机系统是5.1.1, 所以把build.gradle中的 compileSdkVersion 设为25, 然后一编译就报错了。只能改回28, 但是手边没有 Android 9 的手机了。
问题解决了:
1。 原因:之前Android用 android.support 这个库去兼容低版本的系统,然后现在Google把这个库益处了而取而代之的是 androidx 。但是flutter和android studio都没有同步更新。
2。解决方法:
在文件 android/build.gradle 中
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
}
替换为:
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
}
文件 android/gradle.properties 后面加2行
android.enableJetifier=true android.useAndroidX=true
在文件 android/app/build.gradle 中
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
替换为
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
把 dependencies { 中的
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
替换为
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
详情见 https://flutter.dev/docs/development/packages-and-plugins/androidx-compatibility
再启动报 webview-plugin 使用了过时的 API,删掉之。
Flutter App 终于可以在我的手机上启动了
然后点击“添加照片”按钮又报错:“Attempt to invoke virtual method 'android.content.res.XmlResourceParser 。。。。‘
初步判断是没有权限。网上找了一圈方法,大致分为2种方案:(一)是在 AndroidManifest.xml 中加入权限设置, (二)是在使用 image_picker之前用 permission_handler 申请权限,我都照着做了,都不起作用。
最后看到一个总结:要么(一)跟(二)都做,要么都不做,最重要的是要 clean build directory
最后把网上找的各种代码都去掉, 清空build目录,然后就好了