第一个Android Flutter项目hello_world_flutter

官网参考

https://flutter.cn/docs/get-started/

环境配置

https://flutter.cn/docs/get-started/install/windows

1.下载flutter sdk

笔者当时下载最新版本3.3.10
https://storage.flutter-io.cn/flutter_infra_release/releases/stable/windows/flutter_windows_3.3.10-stable.zip

也可以从git仓库中选择版本分支下载

git clone https://github.com/flutter/flutter.git -b stable   

编辑工具设定

1.因为笔者已经安装过AS2021.03.01版本,所以此处是基于AS上安装Flutter插件和Dart插件

Linux 或者 Windows 平台
参考使用下面介绍的步骤:

打开插件偏好设置 (位于 File > Settings > Plugins)

选择 Marketplace (扩展商店),选择 Flutter plugin 和 Dart plugin 然后点击 Install (安装)。

开发体验初探

安装完Flutter插件后,重启AS,就可以新建Flutter项目,指定刚刚下载解压的Flutter SDK目录
在这里插入图片描述
打开 IDE 并选中 New Flutter Project。

选择 Flutter,验证 Flutter SDK 的路径。完成后选择 Next。

输入项目名称(例如HelloWorldFlutter)。

选择 Application 的项目类型,完成后选择 Next。

点击 完成。

等待 Android Studio 完成项目的创建。

![在这里插入图片描述](https://img-blog.csdnimg.cn/6c9ffa51e25547c9948fe640940fa748.png

默认android平台开发语言是kotlin、ios平台开发语言是swift
且默认支持多种平台android\ios\Linux\MacOS\Web\Windows
根据实际需要按需选择,此处默认全选

点击finish,提示dart package只能小写,当前为HelloWorldFlutter(有大写字母)无法创建项目,更改项目名称为hello_world_flutter即可

1.目录结构

在这里插入图片描述
android目录和lib目录

其他平台都有各自的目录(ios、macos、linux、web‘、windows)

lib目录

在这里插入图片描述

main.dart文件如下

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

android目录

![在这里插入图片描述](https://img-blog.csdnimg.cn/27771859556847be924136399931f652.png

绿色标注多了两个AndroidManifest.xml

红色重点文件分析

1.MainActivity.kt
package com.example.hello_world_flutter

import io.flutter.embedding.android.FlutterActivity

class MainActivity: FlutterActivity() {
}

2.build.gradle
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    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.example.hello_world_flutter"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

3.GeneratedPluginRegistrant.java
package io.flutter.plugins;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import io.flutter.Log;

import io.flutter.embedding.engine.FlutterEngine;

/**
 * Generated file. Do not edit.
 * This file is generated by the Flutter tool based on the
 * plugins that support the Android platform.
 */
@Keep
public final class GeneratedPluginRegistrant {
  private static final String TAG = "GeneratedPluginRegistrant";
  public static void registerWith(@NonNull FlutterEngine flutterEngine) {
  }
}

4.AndroidManifest,xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hello_world_flutter">
   <application
        android:label="hello_world_flutter"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

2.编译

在这里插入图片描述
可以看到能指定多个平台

在这里插入图片描述

在这里插入图片描述

点击main.dart绿色run configuration即可开始编译,编译命令为??

3.运行结果

在这里插入图片描述

遇到的问题

问题1:Android Studio中FlutterActivity相关类全部标红,点击无法跳转到类定义

在这里插入图片描述

无法访问io.flutter.embedding.android.FlutterActivity

原因是这个类所在库是在gradle脚本中作为依赖动态添加的,所以as没有在external library中直接展示,需要手动引入依赖

在这里插入图片描述
在flutter sdk目录下的/packages/flutter_tools/gradle/flutter.gradle文件,关键函数addFlutterDependencies,用来动态添加依赖库
在这里插入图片描述
在这里插入图片描述
红色标框是我手动加的日志,绿色标框就是动态加依赖的脚本函数调用

重新执行gradle编译,可以看到debug模式下输出日志如下:
flutter_embedding_debug这个jar包里主要就是FlutterActivity等基础java类库,
arm64_v8a_debug、x86_debug、x86_64_debug不同abi版本对应不同的jar包,原因就是三个jar包里存储的是不同abi下的libflutter.so动态库

在这里插入图片描述

解决方案

所以解决本次标红问题就是通过手动往项目的external library中引入flutter_embedding_debug这个gradle下载的依赖库(另:网上有一种说法是直接引入flutter sdk目录下的flutter.jar,具体路径为flutter sdk根目录\bin\cache\artifacts\engine\android-arm\flutter.jar,也可以,这个jar包里包含了FlutterActivity等基础类库和libflutter.so,所以更好???)

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
此时点击FlutterActivity可以正确跳转到FlutterActivity的定义

解决方案修正

右键android目录作为android工程打开,android gradle工程正常sync后所有的依赖库代码就可以索引到了

猜你喜欢

转载自blog.csdn.net/weixin_41548050/article/details/128565599