Flutter 基本页面结构布局 及 自定义 Widget 文件 分离
一、Flutter 基本页面结构 MaterialApp、Scalfold
一个 Flutter,准确来说基于 Material 设计的 APP,是需要 MaterialApp 和 Scalfold 两个 Widget 组成的
其中 MaterialApp 用来描述 APP 结果,而 Scalfold 用来描述页面的基本结构。
比如下面的代码中:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Postbird Flutter')
),
body: HomeContent(),
),
// theme: ThemeData.dark(),
theme: ThemeData(
primaryColor: Colors.yellow
)
);
}
}
class HomeContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text(
'Postbird 自定义 Widget!',
textDirection: TextDirection.ltr,
style: TextStyle(fontSize: 40, color: Colors.blue),
));
}
}
可以发现 MaterialApp 的 home 参数用来指定首页用哪个 Widget 渲染
而 Scafold
Widget 用来描述一个页面的基本结构,其中 appBar
用来描述导航栏,一般使用 AppBar
Widget ,body
则是页面上正常显示的 Widget。
最终效果如下:
二、 自定义 Widget 并单独拆分文件
项目中我们可能存在大量的自定义 Widget,自定义 Widget 应当单独拆成一个 Widget 文件,Common 的 Widget 更是如此。
自定义 Widget 非常简单,就是正常些 Widget 即可,比如我在 widgets/
目录下写了一个 EachoWidget
:
主要的作用就是输出一个文本,同时可以指定一个背景颜色。
// widgets/EacheWidget.dart
import 'package:flutter/material.dart';
class EchoWidegt extends StatelessWidget {
const EchoWidegt({
@required this.text,
this.backgroundColor,
});
final String text;
final Color backgroundColor;
@override
Widget build(BuildContext context) {
return Center(
child: Container(
color: this.backgroundColor,
child: Text(this.text),
));
}
}
在 main.dart 中引用自定义组件:
和引入 dart 的库是一样的,import './widegts/EchoWidegt.dart';
,引入之后可以直接使用
import 'package:flutter/material.dart';
import './widegts/EchoWidegt.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Postbird Flutter')),
body: HomeContent(),
),
// theme: ThemeData.dark(),
theme: ThemeData(primaryColor: Colors.yellow));
}
}
class HomeContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: EchoWidegt(
text: '啊啊啊啊',
backgroundColor: Colors.pink,
),
);
}
}
效果:
三、完整代码示例
基本 App 页面布局:
自定义 Widget 分离 main.dart
:
自定义 Widget 分离文件 EachoWidget.dart
:
文章已经结束啦
文章版权:Postbird-There I am , in the world more exciting!
本文链接:http://www.ptbird.cn/flutter-self-widget.html
转载请注明文章原始出处 !
扫描二维码,在手机阅读!