Flutter 通过 Widget 嵌套 Widget 来构建UI和执行处理的,Flutter 中万物皆为Widget。
- 无状态组件:StatelessWidget
- 有状态组件:StatefulWidget
//导入Material UI 组件库
import 'package:flutter/material.dart';
//程序入口
void main() {
runApp(const MyApp());
}
//StatelessWidget 无状态组件(简单理解初始化UI后界面内容不变),必须重写build方法
class MyApp extends StatelessWidget {
//构造函数
const MyApp({Key? key}) : super(key: key);
//绘制界面
@override
Widget build(BuildContext context) {
//根布局
return MaterialApp(
//去掉debug图标
debugShowCheckedModeBanner: false,
//应用名称
title: 'Flutter Demo',
theme: ThemeData(
//主题颜色
primarySwatch: Colors.blue,
),
//应用首页路由
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
//StatefulWidget 有状态组件(简单理解初始化UI后界面内容可变)需要结合 State,必须重写createState方法
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({Key? key, required this.title}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
//_类名表示私有,_MyHomePageState 需要继承 State 并且重写build方法
class _MyHomePageState extends State<MyHomePage> {
//计数器
int _counter = 0;
void _incrementCounter() {
//通知框架发生变化,并且重绘页面UI
setState(() {
_counter++;
});
}
//绘制界面
@override
Widget build(BuildContext context) {
//Scaffold 页面脚手架
return Scaffold(
//设置顶部布局
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
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),
),
);
}
}
Widget 中定义的属性必须是 final,如果可变则需要重绘界面。
网友评论