Flutter进阶—布局一个控件

来源:互联网 发布:java试题库及答案 编辑:程序博客网 时间:2024/05/15 12:29

要在Flutter中布局单个控件,创建一个简单的控件并将其显示在屏幕上。在Flutter中,将文本、图标或图像放在屏幕上只需几步。

1、选择一个布局控件来保存对象

根据您希望对齐或约束可见控件的方式,从各个布局控件中进行选择,因为布局控件的特征会传递到包含的子控件。下面示例使用Center(中心),其内容水平和垂直。

2、创建一个控件来保存可见对象

创建一个Text(文本)控件:

new Text('Hello World', style: new TextStyle(fontSize: 32.0))

创建一个Image(图像)控件:

new Image.asset('images/myPic.jpg', fit: BoxFit.cover)

创建一个Icon(图标)控件:

new Icon(Icons.star, color: Colors.red[500])

3、将可见的控件添加到布局控件

如果布局控件有一个child属性,那么它只接受一个子控件,比如Center(中心)或Container(容器)。如果布局控件有一个children属性,则它们接受一个子控件列表,比如Row(行)、Column(列)、ListView(滚动列表)或Stack(层叠)。

将Text(文本)控件添加到Center(中心)控件:

new Center(  child: new Text('Hello World', style: new TextStyle(fontSize: 32.0)))

4、将布局控件添加到页面

一个Flutter应用程序本身就是一个控件,大多数控件都有一个build()方法,在应用程序的构建方法中声明控件将在设备上显示该子控件。

对于material(质感设计)应用程序,您可以将Center(中心)控件直接添加到主页的body属性。

class _MyHomePageState extends State<MyHomePage> {  @override  Widget build(BuildContext context) {    return new Scaffold(      appBar: new AppBar(        title: new Text(widget.title),      ),      body: new Center(        child: new Text('Hello World', style: new TextStyle(fontSize: 32.0)),      ),    );  }}

对于非material(质感设计)应用程序,您可以将Center(中心)控件添加到应用程序的build()方法中:

import 'package:flutter/material.dart';void main() {  runApp(new MyApp());}class MyApp extends StatelessWidget {  @override  Widget build(BuildContext context) {    return new Container(      decoration: new BoxDecoration(color: Colors.white),      child: new Center(        child: new Text('Hello World',            style: new TextStyle(fontSize: 40.0, color: Colors.black87)),      ),    );  }}

请注意,默认情况下,非material(质感设计)应用程序不包括应用栏、标题或背景颜色。如果您希望在非material(质感设计)应用程序中使用这些功能,则必须自己构建它们。此应用程序将背景颜色更改为白色,将文本更改为深灰色以模拟material(质感设计)应用程序。

这里写图片描述

0 0