The first Android Flutter project hello_world_flutter

Official website reference

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

Environment configuration

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

1. Download flutter sdk

The author downloaded the latest version 3.3.10
https://storage.flutter-io.cn/flutter_infra_release/releases/stable/windows/flutter_windows_3.3.10-stable.zip

You can also select the version branch to download from the git repository

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

Edit tool settings

1. Because the author has installed the AS2021.03.01 version, so here is based on the installation of the Flutter plug-in and the Dart plug-in on the AS

For Linux or Windows platform,
refer to the steps described below:

Open the plugin preferences (located in File > Settings > Plugins)

Select Marketplace, choose Flutter plugin and Dart plugin and click Install.

A Preliminary Study of Development Experience

After installing the Flutter plugin, restart the AS to create a new Flutter project, specify the directory of the Flutter SDK that you just downloaded and decompress,
insert image description here
open the IDE and select New Flutter Project.

Select Flutter and verify the path to the Flutter SDK. Select Next when finished.

Enter a project name (eg HelloWorldFlutter).

Select the project type of Application and select Next when finished.

Click Finish.

Wait for Android Studio to finish creating the project.

![Insert picture description here](https://img-blog.csdnimg.cn/6c9ffa51e25547c9948fe640940fa748.png

The default android platform development language is kotlin, the ios platform development language is swift
and supports multiple platforms by default android\ios\Linux\MacOS\Web\Windows
can be selected according to actual needs. Here, all are selected by default.

Click finish, it prompts that the dart package can only be lowercase, currently HelloWorldFlutter (with uppercase letters) cannot create a project, just change the project name to hello_world_flutter

1. Directory structure

insert image description here
android directory and lib directory

Other platforms have their own directories (ios, macos, linux, web', windows)

lib directory

insert image description here

The main.dart file is as follows

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 directory

![Insert picture description here](https://img-blog.csdnimg.cn/27771859556847be924136399931f652.png

There are two more AndroidManifest.xml marked in green

Red key file analysis

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. compile

insert image description here
You can see that multiple platforms can be specified

insert image description here

insert image description here

Click the green run configuration of main.dart to start compiling. What is the compiling command? ?

3. Running results

insert image description here

problems encountered

Question 1: All classes related to FlutterActivity in Android Studio are marked in red, and clicking cannot jump to the class definition

insert image description here

Cannot access io.flutter.embedding.android.FlutterActivity

The reason is that the library where this class is located is dynamically added as a dependency in the gradle script, so as is not directly displayed in the external library, and the dependency needs to be manually introduced

insert image description here
In the /packages/flutter_tools/gradle/flutter.gradle file in the flutter sdk directory, the key function addFlutterDependencies is used to dynamically add dependent libraries. The red
insert image description here
insert image description here
frame is the log I added manually, and the green frame is the script function call for dynamically adding dependencies

Re-execute the gradle compilation, and you can see that the output log in debug mode is as follows:
The jar package flutter_embedding_debug mainly contains basic java libraries such as FlutterActivity, and
different abi versions of arm64_v8a_debug, x86_debug, and x86_64_debug correspond to different jar packages. The reason is that there are three jar packages The libflutter.so dynamic library under different abi is stored

insert image description here

solution

So to solve this red mark problem is to manually introduce flutter_embedding_debug, a dependent library downloaded by gradle, into the external library of the project (another: there is a saying on the Internet that directly imports flutter.jar under the flutter sdk directory, and the specific path is the flutter sdk root directory \bin\cache\artifacts\engine\android-arm\flutter.jar, it is also possible, this jar package contains basic class libraries such as FlutterActivity and libflutter.so, so it is better???)

insert image description here

insert image description here

insert image description here
insert image description here
Clicking on FlutterActivity at this point can correctly jump to the definition of FlutterActivity

solution correction

Right-click the android directory to open it as an android project. After the android gradle project is normally synced, all dependent library codes can be indexed.

Guess you like

Origin blog.csdn.net/weixin_41548050/article/details/128565599