Created with <3 with dartpad.dev.
Created
June 8, 2023 08:21
-
-
Save metal-young/38018749bc02914cd6479c342bf656a6 to your computer and use it in GitHub Desktop.
astonishing-bulb-1058
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const MyApp()); // 运行 MyApp 应用 | |
} | |
class MyApp extends StatelessWidget { // MyApp 是一个无状态组件 | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( // MaterialApp 是一个应用级别的组件,提供了主题、路由等配置 | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const MyHomePage(title: '计数器应用'), // home 属性接收一个组件,作为应用的首页 | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { // MyHomePage 是一个有状态组件 | |
const MyHomePage({Key? key, required this.title}) : super(key: key); | |
final String title; // 这是一个属性,接收一个标题 | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); // createState 方法返回一个状态对象 | |
} | |
class _MyHomePageState extends State<MyHomePage> { // _MyHomePageState 是状态对象 | |
int _counter = 0; // 这是一个状态,记录了点击按钮的次数 | |
void _incrementCounter() { // 这是一个方法,用于增加计数器的值 | |
setState(() { // 调用 setState 方法来更新状态,并重新构建 UI | |
_counter++; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { // build 方法返回一个组件树 | |
return Scaffold( // Scaffold 是一个页面脚手架,提供了常用的页面元素,如:appBar、body、floatingActionButton 等 | |
appBar: AppBar( // appBar 属性接收一个组件,作为页面的头部 | |
title: Text(widget.title), | |
), | |
body: Center( // body 属性接收一个组件,作为页面的主体 | |
child: Column( // Column 是一个垂直布局的组件 | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ // children 属性接收一个组件列表 | |
const Text( | |
'你已经点击了按钮这么多次:', | |
), | |
Text( | |
'$_counter', // 显示计数器的值 | |
style: Theme.of(context).textTheme.headline4, | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( // floatingActionButton 属性接收一个组件,作为页面的浮动按钮 | |
onPressed: _incrementCounter, // onPressed 属性接收一个方法,当按钮被点击时,会调用这个方法 | |
tooltip: '增加', | |
child: const Icon(Icons.add), // child 属性接收一个组件,作为按钮的图标 | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment