Flutter学习笔记之计数器应用
1.创建flutter项目
control+shift+p
=> Flutter: New Project
=> Application
=> 选择一个路径保存项目 => 输入项目名 counter
2.添加项目源码
编辑 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 THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
// 深紫色主题
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
// 应用首页路由
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(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// 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.
//
// 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).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
3.运行示例
在项目根目录运行下面命令,并选择平台即可
>> flutter run
Connected devices:
Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.26100.4946]
Chrome (web) • chrome • web-javascript • Google Chrome 139.0.7258.155
Edge (web) • edge • web-javascript • Microsoft Edge 139.0.3405.125
[1]: Windows (windows)
[2]: Chrome (chrome)
[3]: Edge (edge)
Please choose one (or "q" to quit): 1
Launching lib\main.dart on Windows in debug mode...
Building Windows application... 6.1s
√ Built build\windows\x64\runner\Debug\counter.exe
libpng warning: tRNS: invalid with alpha channel
libpng warning: tRNS: invalid with alpha channel
libpng warning: tRNS: invalid with alpha channel
Syncing files to device Windows... 44ms
Flutter run key commands.
r Hot reload.
R Hot restart.
h List all available interactive commands.
d Detach (terminate "flutter run" but leave application running).
c Clear the screen
q Quit (terminate the application on the device).
A Dart VM Service on Windows is available at: http://127.0.0.1:58378/x_IX2MAzifg=/
The Flutter DevTools debugger and profiler on Windows is available at:
http://127.0.0.1:9101?uri=http://127.0.0.1:58378/x_IX2MAzifg=/
我这里选择的是1,也即是Windows应用,然后就可以看到:
4.代码解析
应用入口为:
void main() {
runApp(const MyApp());
}
同其他语言类似,Flutter应用中 main
函数为应用程序的入口。main
函数调用 runApp
方法,接收一个 Widget
对象来启动Flutter应用。
MyApp
类继承自StatelessWidget
,是Flutter应用。在构建页面时,Flutter会调用组件的build
方法,Widget
的主要工作就是提供一个build
方法来描述如何构建UI界面。MaterialApp
是Material
库中提供的Flutter APP框架,通过它可以设置应用名称、主题、语言、首页及路由列表等。home
为Flutter应用的首页,它也是一个widget。
后面的 MyHomePage
继承自 StatefulWidget
类,表示它是一个有状态的组件(Stateful widget)。一个有状态组件至少由两个类组成:一个 StatefulWidget
类和一个 State
类,StatefulWidget
本身是不可变的,但是 State
类持有的状态在组件生命周期中可能会发生变化。
参考资料
- [1] 《Flutter实战·第二版》