flutter無狀態小部件教程 小白也能看懂

本頭條核心宗旨

歡迎來到「技術剛剛好」作者,「技術剛剛好」是個人維護,每天至少更新一篇Flutter技術文章,實時為大家播報Flutter最新消息。如果你剛好也在關注Flutter這門技術,那就跟我一起學習進步吧,你的贊,收藏,轉發是對我個人最大的支持,維護不易,歡迎關注。

技術剛剛好經歷

近幾年,移動端跨平臺開發技術層出不窮,從Facebook家的ReactNative,到阿里家WEEX,前端技術在移動端跨平臺開發中大展身手,技術剛剛好作為一名Android開發,經歷了從Reactjs到Vuejs的不斷學習。而在2018年,我們的主角變成了Flutter,這是Goolge開源的一個移動端跨平臺解決方案,可以快速開發精美的移動App。希望跟大家一起學習,一起進步!

本文核心要點

使用無狀態小部件我相信很多人都在使用,而且很多項目也在使用,今天就分享個大家。

DEMO

main.dart文件介紹

<code>import 'package:flutter/material.dart';void main() { runApp(MaterialApp( home: MyApp(), // Define the theme, set the primary swatch theme: ThemeData(primarySwatch: Colors.green), ));}class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { // Declare some constants final double myTextSize = 30.0; final double myIconSize = 40.0; final TextStyle myTextStyle = TextStyle(color: Colors.grey, fontSize: myTextSize); var column = Column( // Makes the cards stretch in horizontal axis crossAxisAlignment: CrossAxisAlignment.stretch, children: <widget>[ // Setup the card MyCard( // Setup the text title: Text( "Favorite", style: myTextStyle, ), // Setup the icon icon: Icon(Icons.favorite, size: myIconSize, color: Colors.red)), MyCard( title: Text( "Alarm", style: myTextStyle, ), icon: Icon(Icons.alarm, size: myIconSize, color: Colors.blue)), MyCard( title: Text( "Airport Shuttle", style: myTextStyle, ), icon: Icon(Icons.airport_shuttle, size: myIconSize, color: Colors.amber)), MyCard( title: Text( "Done", style: myTextStyle, ), icon: Icon(Icons.done, size: myIconSize, color: Colors.green)), ], ); return Scaffold( appBar: AppBar( title: Text("Stateless Widget"), ), body: Container( // Sets the padding in the main container padding: const EdgeInsets.only(bottom: 2.0), child: Center( child: SingleChildScrollView(child: column), ), ), ); ; }}// Create a reusable stateless widgetclass MyCard extends StatelessWidget { final Widget icon; final Widget title; // Constructor. {} here denote that they are optional values i.e you can use as: MyCard() MyCard({this.title, this.icon}); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.only(bottom: 1.0), child: Card( child: Container( padding: const EdgeInsets.all(20.0), child: Column( children: <widget>[this.title, this.icon], ), ), ), ); }}/<widget>/<widget>/<code>

謝謝觀看技術剛剛好的文章,技術剛剛好是個人維護,每天至少更新一篇Flutter技術文章,實時為大家播報Flutter最新消息。如果你剛好也在關注Flutter這門技術,那就跟我一起學習進步吧,你的贊,收藏,轉發是對我個人最大的支持,維護不易,歡迎關注。