Flutter入门(一)

简单小案例
  • 修复vscode所有 const 警告抖动(Fix all const warning flutter) settings 配置如下
{
    "[dart]": {
        "editor.formatOnSave": false,
        "editor.formatOnType": false,
        "editor.rulers": [
            80
        ],
        "editor.selectionHighlight": false,
        "editor.suggest.snippetsPreventQuickSuggestions": false,
        "editor.suggestSelection": "first",
        "editor.tabCompletion": "onlySnippets",
        "editor.wordBasedSuggestions": false,
        "editor.codeActionsOnSave": {
            "source.fixAll": true
        }
    },
    "workbench.colorTheme": "One Dark Pro Darker",
    "editor.formatOnPaste": true,
    "editor.fontLigatures": false
}
// 全局组件库
import 'package:flutter/material.dart';

// 启动入口
void main() {
// 启动方法
  runApp(MyApp());
}

// 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
// MaterialApp 整个App盒子 根组件
    return MaterialApp(
// home 首页 Scaffold 当前也骨架
      home: Scaffold(
// appBar 导航
        appBar: AppBar(
          title: Text("导航"),
        ),
// body 主体
        body: HomeContent(),
      ),
// 主题
      theme: ThemeData(primarySwatch: Colors.yellow),
    );
  }
}

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        height: 200.0,
        width: 200.0,
        decoration: BoxDecoration(
            color: Colors.yellow,
            border: Border.all(
              width: 2.0,
              color: Colors.blue,
            )),
        child: const Text(
          '你好Flutter 初来乍到 请多关照',
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 12.0, color: Colors.red),
        ),
      ),
    );
  }
}
加载网络图片
class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 300,
        height: 400,
        decoration: BoxDecoration(
          color: Colors.yellow,
        ),
        child: Image.network(
          "https://img1.baidu.com/it/u=868813610,546932015&fm=253&fmt=auto&app=138&f=JPEG",
          width: 200, // 定义的是组件的大小 不是图片的大小
          height: 200,// 图片是填充到组件的
          fit: BoxFit.none, // 填充方式
        ),
      )
    );
  }
}
圆形图片两种方式
  • 1.使用外层包装 定义包装圆角 使图片填充
  • 2.图片加载方式使用 ClipOval
  • 3.专门处理头像的类CircleAvatar
// CircleAvatar(
//   backgroundImage: NetworkImage("https://img1.baidu.com/it/u=868813610,546932015&fm=253&fmt=auto&app=138&f=JPEG"),
// ),
class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: ClipOval(
          child: Image.network(
            "https://img1.baidu.com/it/u=868813610,546932015&fm=253&fmt=auto&app=138&f=JPEG",
          ),
        ),
        decoration: BoxDecoration(
          color: Colors.yellow
        ),
        width: 300,
        height: 300,
        // decoration: BoxDecoration(
        //   color: Colors.yellow,
        //   // borderRadius: BorderRadius.all(Radius.circular(150)),
        //   borderRadius: BorderRadius.circular(150),
        //   image: DecorationImage(
        //     image: NetworkImage("https://img1.baidu.com/it/u=868813610,546932015&fm=253&fmt=auto&app=138&f=JPEG"),
        //     fit: BoxFit.cover
        //   ),
        // ),
      )
    );
  }
}
加载本地图片
  • 1.新建目录 images/2.0x images/3.0x images/4.0x 分辨率不同
  • 2.修改pubspec.yaml 打开 assets 注意缩进 assert是属于flutter下


    1.png
class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.yellow
        ),
        width: 300,
        height: 300,
        child: ClipOval(
          child: Image.asset(
            "images/2.0x/2.jpg"
          ),
        ),
      )
    );
  }
}
ListView
  • 1 垂直列表
  • 2 垂直图文列表
  • 3 水平列表
  • 4 动态列表
  • 5 矩阵列表
ListTile 垂直列表&垂直图文列表
class HomeContent extends StatelessWidget {
  const HomeContent({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: const EdgeInsets.all(10),
      // ignore: prefer_const_literals_to_create_immutables
      children: [
        const ListTile(
          leading: Icon(
            Icons.search,
            color: Colors.yellow,
            size: 30,
          ),
          trailing: Icon(
            Icons.add_task,
            color: Color.fromARGB(255, 144, 47, 116),
          ),
          title: Text(
            "标题",
            style: TextStyle(
              fontSize: 12
            ),
          ),
          subtitle: Text("二级标题"),
          selected: true,
        ),
        const ListTile(
          leading: Icon(
            Icons.home,
            color: Colors.red,
          ),
          title: Text("垂直列表"),
          subtitle: Text("垂直列表二级标题"),
        ),
        ListTile(
          leading: Image.asset("images/b.png"),
          title: const Text("垂直列表"),
          subtitle: const Text("垂直列表二级标题"),
        ),
      ],
    );
  }
}
水平列表
return ListView(
      scrollDirection: Axis.horizontal,
      children: _getData(),
    );
列表循环
class HomeContent extends StatelessWidget {
  const HomeContent({Key? key}) : super(key: key);

  List _getData1() {
    List listData = [
      {
        "title": "水浒传",
        "author":"施耐庵",
        "imgUrl":"https://www.itying.com/images/flutter/1.png",
      },
      {
        "title": "红楼梦",
        "author": "曹雪芹",
        "imgUrl": "https://www.itying.com/images/flutter/2.png",
      },
      {
        "title": "三国演义",
        "author": "罗贯中",
        "imgUrl": "https://www.itying.com/images/flutter/3.png",
      },
      {
        "title": "西游记",
        "author": "吴承恩",
        "imgUrl": "https://www.itying.com/images/flutter/4.png",
      },
    ];
    return listData;
  }

  List<Widget> _getData() {
    List list = _getData1();
    List<Widget> tempList = list.map((value){
        return ListTile(
          leading: Image.network(value["imgUrl"]),
          title: Text(value["title"]),
          subtitle: Text(value['author']),
        );
    }).toList();
    return tempList;
  }

  // List<Widget> _getData() {
  //   List<Widget> list = [];
  //   for (var i = 0; i < 10; i++) {
  //     list.add(ListTile(
  //       title: Text("我是第$i一个列表"),
  //     ));
  //   }
  //   return list;
  // }

  @override
  Widget build(BuildContext context) {
    return ListView(
      scrollDirection: Axis.horizontal,
      // ignore: prefer_const_literals_to_create_immutables
      children: _getData(),
    );
  }
}
ListView.builder
class HomeContent extends StatelessWidget {
  List list = [];

  HomeContent() {
    for (var i = 0; i < 10; i++) {
      list.add("我是第$i一个列表");
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: list.length,
      itemBuilder: (BuildContext context, int index) {
        return ListTile(
          title: Text(list[index]),
        );
      },
    );
  }
}
class HomeContent extends StatelessWidget {
  List list = [];
  List listData = [
    {
      "title": "水浒传",
      "author": "施耐庵",
      "imgUrl": "https://www.itying.com/images/flutter/1.png",
    },
    {
      "title": "红楼梦",
      "author": "曹雪芹",
      "imgUrl": "https://www.itying.com/images/flutter/2.png",
    },
    {
      "title": "三国演义",
      "author": "罗贯中",
      "imgUrl": "https://www.itying.com/images/flutter/3.png",
    },
    {
      "title": "西游记",
      "author": "吴承恩",
      "imgUrl": "https://www.itying.com/images/flutter/4.png",
    },
  ];

  Widget _getListData(BuildContext context, int index) {
    return ListTile(
      leading: Image.network(listData[index]["imgUrl"]),
      title: Text(listData[index]["title"]),
      subtitle: Text(listData[index]["author"]),
    );
  }
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: listData.length,
      itemBuilder: _getListData,
    );
  }
}
静态网格布局GridView.count
import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("FlutterDemo"),
        ),
        body: HomeContent(),
      ),
    );
  }
}

class HomeContent extends StatelessWidget {

  List listData = [
    {
      "title": "水浒传",
      "author": "施耐庵",
      "imgUrl": "https://www.itying.com/images/flutter/1.png",
    },
    {
      "title": "红楼梦",
      "author": "曹雪芹",
      "imgUrl": "https://www.itying.com/images/flutter/2.png",
    },
    {
      "title": "三国演义",
      "author": "罗贯中",
      "imgUrl": "https://www.itying.com/images/flutter/3.png",
    },
    {
      "title": "西游记",
      "author": "吴承恩",
      "imgUrl": "https://www.itying.com/images/flutter/4.png",
    },
  ];

  List<Widget> _getListData() {
    return listData.map((value){
        return Container(
          decoration: BoxDecoration( // 加边框
            border: Border.all(
              color: Colors.blue,
              width: 0.5,
            ),
          ),
          child: Column( // 一列 上下展示
            children: [
              Image.network(value['imgUrl']),
              const SizedBox(height: 10,),// 设置空盒子高度
              Text(value["title"]),
              Text(
                value["author"],
                style: const TextStyle(
                  fontSize: 12,
                  color: Colors.red,
                ),
              ),
            ],
          ),
        );
    }).toList();
  }

  // List<Widget> _getListData() {
  //   List<Widget> list = [];
  //   for (var i = 1; i <= 12; i++) {
  //     list.add(
  //       Container(
  //         // margin: const EdgeInsets.all(10),
  //         padding: const EdgeInsets.all(10),
  //         alignment: Alignment.center,
  //         color: Colors.yellow,
  //         child: Text(
  //           "这是第$i个文本",
  //           style: const TextStyle(
  //             color: Colors.blue,
  //             fontSize: 12,
  //           ),
  //         ),
  //       )
  //     );
  //   }
  //   return list;
  // }
  
  @override
  Widget build(BuildContext context) {
    return GridView.count(
      crossAxisCount: 2, // 显示多少列
      crossAxisSpacing: 20,// 子Widget左右距离
      mainAxisSpacing: 20,// 子Widget上下距离
      padding: const EdgeInsets.all(10), // 整体加padding
      childAspectRatio: 0.8,//子Widget的宽和高比例
      children: _getListData(),

    );
  }
}
动态网格布局GridView.builder
import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("FlutterDemo"),
        ),
        body: HomeContent(),
      ),
    );
  }
}

class HomeContent extends StatelessWidget {

  List listData = [
    {
      "title": "水浒传",
      "author": "施耐庵",
      "imgUrl": "https://www.itying.com/images/flutter/1.png",
    },
    {
      "title": "红楼梦",
      "author": "曹雪芹",
      "imgUrl": "https://www.itying.com/images/flutter/2.png",
    },
    {
      "title": "三国演义",
      "author": "罗贯中",
      "imgUrl": "https://www.itying.com/images/flutter/3.png",
    },
    {
      "title": "西游记",
      "author": "吴承恩",
      "imgUrl": "https://www.itying.com/images/flutter/4.png",
    },
  ];

  Widget _getListData(BuildContext context, int index) {
    return Container(
      decoration: BoxDecoration( // 加边框
        border: Border.all(
          color: Colors.blue,
          width: 0.5,
        ),
      ),
      child: Column( // 一列 上下展示
        children: [
          Image.network(listData[index]['imgUrl']),
          const SizedBox(height: 10,),// 设置空盒子高度
          Text(listData[index]["title"]),
          Text(
            listData[index]["author"],
            style: const TextStyle(
              fontSize: 12,
              color: Colors.red,
            ),
          ),
        ],
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10),
      child: GridView.builder(
        itemCount: listData.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, // 显示多少列
          crossAxisSpacing: 20, // 子Widget左右距离
          mainAxisSpacing: 20, // 子Widget上下距离
          childAspectRatio: 0.8, //子Widget的宽和高比例
        ), 
        itemBuilder: _getListData,
      ),
    );
  }
}
Padding && Row & Column 边距&水平&垂直组件
Padding(
  padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
  child: Text("Padding 组件"),
);
Row(
  children: const [
    Text("row组件"),
    Text("row组件"),
  ],
);

import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("FlutterDemo"),
        ),
        body: const HomeContainer(),
      ),
    );
  }
}

class HomeContainer extends StatelessWidget {
  const HomeContainer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 400,
      width: 400,
      decoration: BoxDecoration(
        border: Border.all(
          color: Colors.black,
          width: 1,
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly, // 主轴
        crossAxisAlignment: CrossAxisAlignment.end, // 次轴
        children: [
          IconContainer(
            Icons.home,
            color: Colors.blue,
          ),
          IconContainer(
            Icons.search,
            color: Colors.orange,
          ),
          IconContainer(
            Icons.assessment,
            color: Colors.red,
          ),
        ],
      ),
    );
  }
}

// ignore: must_be_immutable
class IconContainer extends StatelessWidget{
  IconData icon;
  Color color;
  double size;

  IconContainer(this.icon,
    {Key? key, this.size = 32.0,
    this.color = Colors.white}) : super(key: key);

  @override
  Widget build(Object context) {
    return Container(
      width: 100,
      height: 100,
      color: color,
      child: Center(
        child: Icon(
          icon,
          size: size,
          color: Colors.white,
        ),
      ),
    );
  }
}
Expanded 相当于Flex 自适应
import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("FlutterDemo"),
        ),
        body: const HomeContainer(),
      ),
    );
  }
}

class HomeContainer extends StatelessWidget {
  const HomeContainer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          flex: 1,
          child: IconContainer(
            Icons.home,
            color: Colors.blue,
          ),
        ),
        Expanded(
          flex: 2,
          child: IconContainer(
            Icons.search,
            color: Colors.orange,
          ),
        ),
        Expanded(
          flex: 2,
          child: IconContainer(
            Icons.anchor,
            color: Colors.red,
          ),
        ),
      ],
    );
  }
}

// ignore: must_be_immutable
class IconContainer extends StatelessWidget{
  IconData icon;
  Color color;
  double size;

  IconContainer(this.icon,
    {Key? key, this.size = 32.0,
    this.color = Colors.white}) : super(key: key);

  @override
  Widget build(Object context) {
    return Container(
      width: 100,
      height: 100,
      color: color,
      child: Center(
        child: Icon(
          icon,
          size: size,
          color: Colors.white,
        ),
      ),
    );
  }
}
Stack层叠组件 Align&Positioned使用
import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("FlutterDemo"),
        ),
        body: const HomeContainer(),
      ),
    );
  }
}

class HomeContainer extends StatelessWidget {
  const HomeContainer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 220,
        height: 320,
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.black,
            width: 1.0
          ),
        ),
        child: Stack(
          // alignment: Alignment.center,
          children: [
            Align(
              alignment: Alignment.bottomLeft,
              child: Container(
                width: 200,
                height: 300,
                color: Colors.red,
              ),
            ),
            const Align(
              alignment: Alignment.topRight,
              child: Text("我是文本"),
            ),
            const Positioned(
              left: 10,
              top: 40,
              child: Text("我是文本111"),
            ),
          ],
        ),
      )
    );
  }
}
AspectRatio 宽高比 相对于外层组件
import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("FlutterDemo"),
        ),
        body: const HomeContainer(),
      ),
    );
  }
}

class HomeContainer extends StatelessWidget {
  const HomeContainer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 2.0/1.0,
      child: Container(
        color: Colors.red,
      ),
    );
  }
}
Card组件
import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("FlutterDemo"),
        ),
        body: const HomeContainer(),
      ),
    );
  }
}

class HomeContainer extends StatelessWidget {
  const HomeContainer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        Card(
          margin: const EdgeInsets.all(10),
          child: Column(
            children: const [
              ListTile(
                title: Text(
                  "张三",
                  style: TextStyle(fontSize: 20),
                ),
                subtitle: Text("猴子"),
              ),
              ListTile(
                title: Text("电话: xxxxxxxx"),
              ),
              ListTile(
                title: Text("地址: xxxxxxxx"),
              ),
            ],
          ),
        ),
        Card(
          margin: const EdgeInsets.all(10),
          child: Column(
            children: const [
              ListTile(
                title: Text(
                  "李四",
                  style: TextStyle(fontSize: 20),
                ),
                subtitle: Text("套猴子"),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
Wrap 组件 类似流布局
import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("FlutterDemo"),
        ),
        body: const HomeContainer(),
      ),
    );
  }
}

class HomeContainer extends StatelessWidget {
  const HomeContainer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 10,
      children: const [
        MyButton("Java"),
        MyButton("Php"),
        MyButton("Dart"),
        MyButton("Flutter"),
        MyButton("Mysql"),
        MyButton("Nginx"),
        MyButton("Linux"),
      ],
    );
  }
}

class MyButton extends StatelessWidget{
  final String text;

  // ignore: use_key_in_widget_constructors
  const MyButton(this.text);

  @override
  Widget build(BuildContext context) {
    return OutlinedButton(
      onPressed: (){
        print("点击了");
      }, 
      child: Text(text),
    );
  }
}
StatefulWidget 有状态组件 页面绑定数据 改变页面数据
import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("FlutterDemo"),
        ),
        body: const HomeContainer(),
      ),
    );
  }
}

class HomeContainer extends StatefulWidget {
  const HomeContainer({Key? key}) : super(key: key);

  @override
  State<HomeContainer> createState() => _HomeContainerState();
}

class _HomeContainerState extends State<HomeContainer> {
  int countNum = 1;

  @override
  Widget build(BuildContext context) {

    return Container(
      alignment: Alignment.center,
      child:Column(
        children: [
          const SizedBox(
            height: 200,
          ),
          Chip(label: Text('$countNum')),
          const SizedBox(
            height: 20,
          ),
          OutlinedButton(
            onPressed: (){
              // 有状态组件里才有
              setState(() {
                countNum++;
              });
              print(countNum);
            }, 
            child: const Text("点击"),
          ),
        ],
      )
    );
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容