Flutter学习笔记-Widget
在Flutter中,Widget是构建用户界面的基本单位。每个Widget都是一个StatelessWidget
或者StatefulWidget
类的实例。
StatelessWidget是不可变的,它的状态不会改变。每次调用build方法都会返回相同的结果。
StatefulWidget可以在其生命周期内改变状态,通过使用State
对象来保存状态。
以下是一个简单的Flutter应用程序的代码示例,它包含一个标题为"Hello, World!"的MaterialApp。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Hello, World!'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
在这个例子中,MyApp
是一个StatelessWidget
,它创建了一个带有标题和主题的MaterialApp
。MyHomePage
是一个StatefulWidget
,它有一个状态_MyHomePageState
,可以通过点击FloatingActionButton来增加计数。这个例子展示了如何在Flutter中创
评论已关闭