Configuración del entorno Flutter (entorno window10) la versión más completa

Para participar en flutter, la primera es la configuración del entorno, esta premisa es que se hayan instalado Android Studio y el correspondiente SDK de Android. No hay mucha tontería, mira los pasos específicos:

Entorno dependiente de la configuración

  1. javaConfiguración del entorno por Baidu,
  2. PythonConfiguración del entorno por Baidu
  3. nodeMedio ambiente Baidu

[Error en la transferencia de la imagen del enlace externo. El sitio de origen puede tener un mecanismo de enlace anti-sanguijuelas. Se recomienda guardar la imagen y subirla directamente (img-kBo3AuV5-1604457219364) (https://oss.wangmiaozero.cn//images /media/flutter3.png)]
hoyo de aleteo

Descarga de SDK

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

  1. Descomprimir copia de archivoC:\flutter\bin
  2. Vaya a la ruta de la variable de entorno del sistema para configurar
  3. Lo puse enG:\flutter\bin

必须配置以下
Configure la duplicación doméstica. Busque esta computadora en el escritorio -> haga clic derecho y seleccione propiedades -> configuración avanzada del sistema -> variables de entorno -> busque variables de usuario -> haga clic en nuevo

PUB_HOSTED_URL=https://pub.flutter-io.cn

FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn

Reinicia la computadora

  1. Abra cmd e ingrese para flutter doctorverificar el archivo de configuración que falta

  2. Continúe configurando la configuración del SDK
    para las variables de entorno del usuario(这个可以不配置)

ANDROID_HOME=D:\AndroidSDK //该sdk地址是你安装Android studio的时候配置的sdk的地址

必须配置以下

¡Aparece un signo de exclamación! Algunas licencias de Android no se aceptan. Para resolver esto, ejecute: flutter doctor --android-license Siga su entrada flutter doctor --android-licensesy vaya hasta el final.

  1. Android studioInstale el fluttercomplemento dentro

hoyo de aleteo
hoyo de aleteo

  1. Después de la instalación, reinicie la computadora

Mensaje de error: la extensión Flutter no está instalada; instalar desde

Vaya a vscode e instale el complemento flutter, está bien

Mensaje de advertencia: dispositivo conectado

  1. Ninguna máquina virtual instalada

Hoyo uno

  • Cuando ingresa al flutter doctorentorno de verificación, debe estar todo verde y marcado, excepto por el problema de advertencia de la máquina virtual
  • Entonces estás atrapado en este lugar por un día, dos días. O una semana. Incluso quieres darte por vencido y no quieres aprender. Quéjate de que debes aprender react-native en primer lugar
  • De hecho, el problema es muy simple. Cuando haces clic en la installdescarga de la derecha SDK, solo puedes esperar lentamente. Puede fallar durante aproximadamente una semana. Espera lentamente, no te rindas.
  • Una vez instalado arriba G:\flutter\bin, SDKpon el tuyoG:\flutter\flutter
  • Te sugiero que descargues al G:\flutter\fluttercatálogo
    hoyo de aleteo

Hoyo dos

  • Aún atascado, es posible que tu SDKdescarga no sea buena o que tu velocidad de Internet no sea buena. Por lo general, este lugar estará bien en unos segundos.

hoyo de aleteo

Android Studio crea un nuevo proyecto Flutter

  1. Abre Andorid Studio, aparecerá la siguiente interfaz, seleccionamos el segundo elemento y creamos un nuevo proyecto de Flutter.
    (Si crea un nuevo proyecto por primera vez, puede que sea un poco lento. Esto puede estar relacionado con una computadora de 700 yuanes que es técnicamente más gorda. Por favor ignore esta oración).
打开第二个窗口后,选择第一个选项Flutter Application(flutter应用)。

![flutter坑](https://img-blog.csdnimg.cn/img_convert/e231f60a5bc8ae21ad851acc4b5015e9.png)

这步完成后,系统就会自动为我们创建一个Flutter项目(新建项目的过程也是很慢的,它要去谷歌下载gradle,这个东西很容下载失败,如果失败,可以多反复试几次)。

# 安装AVD虚拟机

1. 现在需要一个虚拟机来运行我们的程序,可以点击`Android Studio`中的上方菜单`tool -AVD Manager`选项。

2. 出现新建菜单,选择`Create Virtual Device.....`如果你一个虚拟机也没建过,这个选项在对话框的中间

3. 选择虚拟机类型,这个你随意选就好,我选择的是`Nexus 5x`。(如果你屏幕小,就选择一个小屏幕的虚拟机)

4. 选择系统,这里尽量选择最新的,我选择了`Android 9.0`系统,选择好后,又是一个漫长的等待过程。

5. 安装好后,点击开始按钮,运行虚拟机了(第一次运行,需要安装系统,会慢一些),运行起来后

# Flutter项目启动

> 虚拟机运行以后,可以点击`debug`按钮,让Flutter程序跑起来。如果你幸运的话,你的Flutter程序经过编译后,就会跑起来了。(这种幸运的机会很小,总会碰到一些小错误,我在这里介绍两个常见的错误)。

Hoyo tres

Al depurar un proyecto, el error más común es un error similar al siguiente.

![flutter坑](https://oss.wangmiaozero.cn//images/media/flutter6.png)
![flutter坑](https://oss.wangmiaozero.cn//images/media/flutter5.png)
Launching lib/main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
* Error running Gradle:
ProcessException: Process "/Users/rabbit/develop/android/flutter_app/android/gradlew" exited abnormally:
Project evaluation failed including an error in afterEvaluate {}. Run with --stacktrace for details of the afterEvaluate {} error.

FAILURE: Build failed with an exception.

* Where:
Build file '/Users/rabbit/develop/android/flutter_app/android/app/build.gradle' line: 25

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not resolve all files for configuration 'classpath'.
   > Could not find lint-gradle-api.jar (com.android.tools.lint:lint-gradle-api:26.1.2).
     Searched in the following locations:
         https://jcenter.bintray.com/com/android/tools/lint/lint-gradle-api/26.1.2/lint-gradle-api-26.1.2.jar

* 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 0s
  Command: /Users/rabbit/develop/android/flutter_app/android/gradlew app:properties

Finished with error: Please review your Gradle project setup in the android/ folder.

La causa de este problema sigue siendo un problema específico de China. La solución es cambiar el enlace de Ali (1.0 ha solucionado este problema, no es necesario restablecerlo).

El primer paso: Modifique androidlos build.gradlearchivos en el directorio debajo del proyecto google()y jcenter()elimine las dos líneas y. Cambie al enlace de Ali.

maven { url 'https://maven.aliyun.com/repository/google' }
maven { url 'https://maven.aliyun.com/repository/jcenter' }
maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }

como sigue:

buildscript {
    repositories {
        //  google()
        //  jcenter()
        maven { url 'https://maven.aliyun.com/repository/google' }
        maven { url 'https://maven.aliyun.com/repository/jcenter' }
        maven { url 'http://maven.aliyun.com/nexus/content/groups/public'}
        }
        dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
    }
}

allprojects {
    repositories {
        // google()
        // jcenter()
        maven { url 'https://maven.aliyun.com/repository/google' }
        maven { url 'https://maven.aliyun.com/repository/jcenter' }
        maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Tenga en cuenta que se han modificado dos partes, no solo modifique una.

Paso 2: Modifique el archivo flutter.gradle en el paquete Flutter SDK. Este directorio debe cambiarse de acuerdo con la ubicación de su SDK. Por ejemplo, lo puse en el directorio Flutter del Disco G, y la ruta es esta.

G:\flutter\flutter\packages\flutter_tools\gradle

Abra el archivo para modificarlo y modifique el código de la siguiente manera (de hecho, es suficiente con cambiar a la ruta de Ali).

buildscript {
    repositories {
        //jcenter()
        // maven {
        //     url 'https://dl.google.com/dl/android/maven2'
        // }
        maven{
            url 'https://maven.aliyun.com/repository/jcenter'
        }
        maven{
            url 'http://maven.aliyun.com/nexus/content/groups/public'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
    }
}

Luego, depúralo de nuevo y básicamente puede iniciarse.

El primer código general de HelloWorld

Vamos a escribir rápidamente una estructura simple. Esta interfaz solo contiene dos partes, la barbarra azul en el orden de la cabeza y el contenido en el área central de la pantalla. (Consulte el código a continuación)

Este código está escrito en el \lib\main.dartarchivo del directorio raíz , que es el Flutterarchivo principal.

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: 'Flutter Demo',
      home:Scaffold(
        appBar: AppBar(
            title:Text('Flutter Demo 学习')
        ),
        body: Center(
         /* child: Text('Hello World,你好,flutter,222222222222222222222222222222222Hello World,你好,flutter',
            textAlign: TextAlign.center,// 文字居中
          //  textAlign: TextAlign.left,// 文字左
            // textAlign: TextAlign.right,// 文字右
           //  textAlign: TextAlign.start,// 文字开始
            //textAlign: TextAlign.end,// 文字结束
            maxLines: 1,// 最多显示多少行
            overflow: TextOverflow.ellipsis,// 显示三个点点
           // overflow: TextOverflow.fade,// 从上到下的一个渐变效果
            style: TextStyle(
              fontSize: 25,
              color: Color.fromARGB(255, 255, 125, 125),
              decoration: TextDecoration.underline,// 加入下划线
           //   decorationStyle: TextDecorationStyle.solid,// 加入下滑线样式,实线,虚线等等
            ),
          ),*/
          child: Container(
            // Container相当于div
            child: new Text('hello flutter',style: TextStyle(fontSize: 20),),
            alignment: Alignment.center,// alignment 子元素对齐
            //alignment: Alignment.bottomCenter,// 底部居中对齐
           // alignment: Alignment.bottomLeft,// 底部左边对齐
          //  alignment: Alignment.bottomRight,// 底部右边对齐
          //  alignment: Alignment.topCenter,// 顶部居中对齐
            // alignment: Alignment.topLeft,// 顶部左边对齐
            //  alignment: Alignment.topRight,// 顶部右边对齐
            width: 500.0,
            height: 400.0,
            color: Colors.lightBlue,// 设置背景颜色
          ),
        ),
      )
     /* theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),*/
    //  home: MyHomePage(title: 'Flutter Demo 学习'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // 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
  _MyHomePageState 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>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Configuración del entorno Flutter (entorno MAC OS)
Configuración del entorno Flutter (entorno window10)

Supongo que te gusta

Origin blog.csdn.net/weixin_43764814/article/details/108354047
Recomendado
Clasificación