1. Summary of Flutter usage (RichText, Container)

1. Create a Flutter project

 flutter create DemoName

2. Run the project

flutter run -d ‘iPhone 14 Pro Max’

Note: When using Android Studio, choose the Android emulator to run the project. If the project path has a Chinese name: Then run an error. If you use the terminal to run the Android emulator directly under the project path, you can execute the following command

flutter run -d ‘Android SDK built for x86’
No supported devices found with name or id matching 'Android SDK built for x86'.
The following devices were found:

At this time, the corresponding device name and device ID will be output, for example, select the Xiaomi device ID "46ffd0ad" currently connected to the USB to execute

flutter run -d ‘46ffd0ad’

will run on the current phone

3. When modifying the current project, enter r in the current running situation to execute the hot reload refresh interface

4. When creating a Flutter project, the difference between FlutterPlugin and Flutter Package is,

 The FlutterPlugin plug-in is suitable for iOS-native or Android-native Dart third-party packages,

 FlutterPackage is a three-party package suitable for pure Dart language applications, shaped like a new widget

 FlutterModule for hybrid development

5. When the project runs stuck,

  • Use Command + Q to forcibly end the project, then the next time you use Android Studio, it will read the previous cache file. If the cache is retrieved, it will return to the previous project. Before it is retrieved, it will affect the opening of the new project, causing Stuck phenomenon. At this time, you need to delete the cache file
rm ~/opt/flutter/bin/cache/lockfile 

6. Initial use of Material App

  1. material.dart is equivalent to UIKit in iOS
  2. runApp is equivalent to UIApplication
  3. Center is a position control
  4. child is equivalent to child control
  5. In flutter, if there is only one line of code inside, it can be abbreviated with an arrow symbol: void main() => runApp(MyWidget());
  6. All widgets in Flutter are divided into two categories: stateful Stateful and stateless Stateless, stateless is an immutable style; stateful is essentially a stateless component, but it will retain the state.
  7. How to display a widget on the interface?
    • A rendering method is needed: the build method, which puts widgets in the widget rendering tree, and renders progressively from the first one. Return the rendering style in the build method.
  1. Click Text to enter it to see the parameter implementation
    1. The parameters are optional, and default values ​​can also be set for them.
    2. final means immutable parameters, var means variable parameters
  1. Redefine a text type final _textStyle = TextStyle();
  2. The code block abbreviation stl will create a StatelessWidget code block, and stful will create a StatefulWidget code block
  3. MaterialApp encapsulates a series of components that are easy to develop
  4. Scaffold has an interface with navigation bar properties, which is equivalent to NavigationController
import 'package:flutter/material.dart';//1.相当于iOS中的UIKit
// 以下都属于Dart语法、
// void main(){
//   //2.runApp相当于UIApplication
//   // runApp(
//   //   //3.Center是一个位置控件
//   //   Center(
//   //     //4.child相当于子控件
//   //     child: MyWidget(),
//   //   )
//   // );
//   //上边代码可以改为
//   runApp(MyWidget());
// }
//2、在flutter中,如果内部只有一行代码、可以简写为如下:
// void main() => runApp(MyWidget());
void main() => runApp(App());
// 也就是 => 代表了 {}
// Command + S保存后可以实现热更新
/*
5.在Flutter中所有的Widget小部件分为两大类:有状态的Stateful和无状态的Stateless、
无状态为不可变样式;有状态本质上也是无状态部件,但是它会将状态保留下来。
*/
//6.创建一个Widget,也就是一个类: MyWidget继承于 StatelessWidget无状态部件
class MyWidget extends StatelessWidget{
  /*
  7.如何将一个部件显示到界面上?
  需要一个渲染方法:build方法,它会将小部件放到小部件渲染树中去,从第一个开始逐步渲染。
  在build方法中返回渲染样式。
  */
  @override
  Widget build(BuildContext context) {
    //9.重定义一个文字类型
    final _textStyle = TextStyle(
      color: Colors.cyan,//文字颜色
      fontSize: 30,//文字大小
      fontWeight: FontWeight.bold,
    );
    return Center(
      child: Text('Hello My Flutter',
        textDirection: TextDirection.ltr,
        style: _textStyle,),
    );
  }
  Widget func() {
    return Text('Hello My Flutter', textDirection: TextDirection.ltr,);
  }
}
//8. 在点击Text进入其中可以看到参数实现
/*
  * 其中的参数都为可选参数、也可以为其设置默认值。
  * final表示不可变参数、var表示可变参数
* */
//10.代码块简写 stl 会创建一个 StatelessWidget代码块, stful会创建一个StatefulWidget代码块
class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 10.1 MaterialApp封装好一系列的便于开发的组件
    return MaterialApp(
      //11. Scaffold具备导航条属性的界面,相当于NavigationController
      home: Scaffold(
        appBar: AppBar( // 导航条
          title: Text('Flutter Demo'),//导航条名称
          foregroundColor: Colors.red,
        ),
        body: MyWidget(), //导航条之外的body
      ),
      theme: ThemeData( //主题
        //Flutter 2.5之后废弃primaryColor,采用colorScheme
        // primaryColor: Colors.black,
        colorScheme: ColorScheme.light().copyWith(primary: Colors.black),
      ),
    );
  }
}

7. ListView use and summary

  • ListView is equivalent to TableView, and what needs to be filled is the content of the ListView.builder protocol
  • Among them, itemCount is equivalent to numOfRows, and there is no Section concept in Flutter
  • The itemBuilder(BuildContext context,int index){} is equivalent to the cellForRow method
  • SizedBox() is a margin placeholder method
  • Image.network() is the method to load network images
  • There are three types of child in Container when setting:
    • Column vertical layout,
    • Row horizontal layout,
    • Stack level layout
import 'package:flutter/material.dart';//1.相当于iOS中的UIKit
import 'model/car.dart'; //导入头文件
//2、在flutter中,如果内部只有一行代码、可以简写为如下:
// void main() => runApp(MyWidget());
void main() => runApp(App());
class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
      theme: ThemeData(
        colorScheme: ColorScheme.light().copyWith(primary: Colors.cyan),
      ),
    );
  }
}
  • Create a stateless component
// 12.创建一个无状态的Widget
class Home extends StatelessWidget {
  // _ 表示私有方法
  Widget _cellForRow(BuildContext context,int index){
    // Container相当于前端中的div
    return Container(
      color: Colors.white,//背景色
      // height: 20,// 给高度、默认填充全屏
      margin: EdgeInsets.all(10),
      // Image.network加载网络图片
      // child: Image.network(datas[index].imageUrl),
      child: Column( //Column 纵向布局、Row横向布局、Stack层级布局
        children: <Widget>[
          Image.network(datas[index].imageUrl),
          //文字和图片的空白距离
          SizedBox(height: 10,),
          Text(
            datas[index].name,
            style: TextStyle(
              fontWeight: FontWeight.w800,
              fontSize: 18.0,//字体大小
              fontStyle: FontStyle.values[1],//斜体
            ),
          ),
        ],
      ),
      // 边距设置为底部5
      // margin: EdgeInsets.only(bottom: 5),
    );
  }
  @override
  Widget build(BuildContext context) {
      return Scaffold(
        backgroundColor: Colors.grey[100],
        appBar: AppBar(
          title: Text('FlutterDemo'),
        ),
        body: ListView.builder( // ListView相当于TableView、
          itemCount: datas.length, // numberOfItem, 在Flutter中没有Section概念
          //相当于 cellForRow
          itemBuilder: _cellForRow,
        ),
      );
  }
}

8. Run the Flutter project and report an error dump failed because resource AndroidManifest.xml not found

  • At this time, go back to the project root directory and execute the terminal
$flutter clean
  • Clear the cached build file and execute it again
$flutter create .
  • Regenerate compiled files

9. Re-encapsulate the use of the above ListView and create a listview_demo.dart file

import 'package:flutter/material.dart';
import 'car.dart';
class ListViewDemo extends StatelessWidget {
  Widget _cellForRow(BuildContext context,int index){
    // Container相当于前端中的div
    return Container(
      color: Colors.white,//背景色
      // height: 20,// 给高度、默认填充全屏
      margin: EdgeInsets.all(10),
      // Image.network加载网络图片
      // child: Image.network(datas[index].imageUrl),
      child: Column( //Column 纵向布局、Row横向布局、Stack层级布局
        children: <Widget>[
          Image.network(datas[index].imageUrl),
          //文字和图片的空白距离
          SizedBox(height: 10,),
          Text(
            datas[index].name,
            style: TextStyle(
              fontWeight: FontWeight.w800,
              fontSize: 18.0,//字体大小
              fontStyle: FontStyle.values[1],//斜体
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder( // ListView相当于TableView、
        itemCount: datas.length, // numberOfItem, 在Flutter中没有Section概念
        //相当于 cellForRow
        itemBuilder: _cellForRow,
    );
  }
}
  • At this point the call to the main.dart file is
import 'package:flutter/material.dart';
import 'model/listview_demo.dart';
//widget
void main() => runApp(App());
class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
      theme: ThemeData(
        primaryColor: Colors.yellow,
      ),
    );
  }
}
class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: Text('FlutterDemo'),
      ),
      body: ListViewDemo(),
    );
  }
}

10. Use of Text text

  • Text assignment can be done by string interpolation: ${_title}
  • Customizable TextStyle
  • Text maximum number of lines: maxLines
  • Text overflow style: overflow
class TextDemo extends StatelessWidget {
  final TextStyle _textStyle = TextStyle(
    fontSize: 16.0, //文字大小
  );
  final String _title = 'iOS 性能优化';
  final String _teacher = 'Holothurian';
  @override
  Widget build(BuildContext context) {
    //1、文本赋值
    return Text(
      '《${_title}》---$_teacher 效率主要是指代码的执行效率、动画的流畅度、应用的冷启动时间和热启动时间、网络通信的阻塞时间等等;消耗主要是指内存的消耗、有没有内存泄漏、CPU的占用率、耗电与应用程序包大小等等;',
      textAlign: TextAlign.center,
      style: _textStyle,
      maxLines: 4,//文字行数
      overflow: TextOverflow.ellipsis,//文字溢出样式:省略号
    );
  }
}

11. Rich Text RichText

  • RichText means rich text
  • TextStyle represents the text style
  • TextSpan represents the style and gesture interaction of the specified text fragment
class RichTextDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 2.RichText 富文本
    return RichText(
        text: TextSpan(
          text: '《iOS 性能优化》',
          style: TextStyle(
              fontSize: 30,
              color: Colors.red
          ),
          children: <TextSpan>[
            TextSpan(
              text: 'Holothurian',
              style: TextStyle(
                  fontSize: 25,
                  color: Colors.cyan
              ),
            ),
            TextSpan(
              text: '效率主要是指代码的执行效率、动画的流畅度、应用的冷启动时间和热启动时间、网络通信的阻塞时间等等;消耗主要是指内存的消耗、有没有内存泄漏、CPU的占用率、耗电与应用程序包大小等等;',
              style: TextStyle(
                  fontSize: 20,
                  color: Colors.black
              ),
            )
          ],
        )
    );
  }
}
  • renderings

12. Container usage supplement

  • margin represents the outer margin
  • padding represents inner margin
  • When the Container child control has no child content, it will not be displayed
class BaseWidgetDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.yellow,
      child: Row(//横向布局
        children: <Widget>[
          // 当Container子控件没有child内容时、不会显示
          Container(
            // 外边距
            margin: EdgeInsets.only(top: 20),
            // 内边距
            padding: EdgeInsets.only(left: 10,right: 10,top: 10,bottom: 10),
            color: Colors.red,
            child: Icon(Icons.add),
            // height: 40,
          ),
          Container(
            color: Colors.red,
            child: Icon(Icons.add_a_photo),
          ),
        ],
      ),
    );
  }
}
  • renderings

Guess you like

Origin blog.csdn.net/SharkToping/article/details/130513942