Flutter for Other Platforms — iOS, Android, Web, React Native, Xamarin
source link: https://medium.com/ionicfirebaseapp/flutter-for-other-platforms-ios-android-web-react-native-xamarin-edd627022a6c
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Flutter for other Platforms
Now flutter for all other platforms developers.
So, Are you coming from another platform? No need to worried now check the documentation for other platforms developer
iOS Developer Docs for Flutter: iOS
Android Developer Doc for Flutter: Android
Web Developer Docs for Flutter: Web
React Native Developer Docs for Flutter: React Native
Xamarin Developer Docs for Flutter: Xamarin
Flutter for iOS developers
This document is for iOS developers looking to apply their existing iOS knowledge to build mobile apps with Flutter. If you understand the fundamentals of the iOS framework then you can use this document as a way to get started learning Flutter development.
Before diving into this doc, you might want to watch a 15-minute video from the Flutter Youtube channel about the Cupertino package.
What is the equivalent of a UIView in Flutter?
How is react-style, or declarative , programming different than the traditional imperative style? For a comparison, see Introduction to declarative UI .
On iOS, most of what you create in the UI is done using view objects, which are instances of the UIView
class. These can act as containers for other UIView
classes, which form your layout.
In Flutter, the rough equivalent to a UIView
is a Widget
. Widgets don’t map exactly to iOS views, but while you’re getting acquainted with how Flutter works you can think of them as “the way you declare and construct UI”.
However, these have a few differences to a UIView
. To start, widgets have a different lifespan: they are immutable and only exist until they need to be changed. Whenever widgets or their state change, Flutter’s framework creates a new tree of widget instances. In comparison, an iOS view is not recreated when it changes, but rather it’s a mutable entity that is drawn once and doesn’t redraw until it is invalidated using setNeedsDisplay()
.
Furthermore, unlike UIView
, Flutter’s widgets are lightweight, in part due to their immutability. Because they aren’t views themselves, and aren’t directly drawing anything, but rather are a description of the UI and its semantics that get “inflated” into actual view objects under the hood.
Flutter includes the Material Components library. These are widgets that implement the Material Design guidelines . Material Design is a flexible design system optimized for all platforms , including iOS.
But Flutter is flexible and expressive enough to implement any design language. On iOS, you can use the Cupertino widgets to produce an interface that looks like Apple’s iOS design language .
How do I update widgets?
To update your views on iOS, you directly mutate them. In Flutter, widgets are immutable and not updated directly. Instead, you have to manipulate the widget’s state.
This is where the concept of Stateful vs Stateless widgets comes in. A StatelessWidget
is just what it sounds like—a widget with no state attached.
StatelessWidgets
are useful when the part of the user interface you are describing does not depend on anything other than the initial configuration information in the widget.
For example, in iOS, this is similar to placing a UIImageView
with your logo as the image
. If the logo is not changing during runtime, use a StatelessWidget
in Flutter.
If you want to dynamically change the UI based on data received after making an HTTP call, use a StatefulWidget
. After the HTTP call has completed, tell the Flutter framework that the widget’s State
is updated, so it can update the UI.
The important difference between stateless and stateful widgets is that StatefulWidget
s have a State
object that stores state data and carries it over across tree rebuilds, so it’s not lost.
If you are in doubt, remember this rule: if a widget changes outside of the build
method (because of runtime user interactions, for example), it’s stateful. If the widget never changes, once built, it’s stateless. However, even if a widget is stateful, the containing parent widget can still be stateless if it isn’t itself reacting to those changes (or other inputs).
The following example shows how to use a StatelessWidget
. A common StatelessWidget
is the Text
widget. If you look at the implementation of the Text
widget you’ll find it subclasses StatelessWidget
.
Text( 'I like Flutter!', style: TextStyle(fontWeight: FontWeight.bold), );
If you look at the code above, you might notice that the Text
widget carries no explicit state with it. It renders what is passed in its constructors and nothing more.
But, what if you want to make “I Like Flutter” change dynamically, for example when clicking a FloatingActionButton
?
To achieve this, wrap the Text
widget in a StatefulWidget
and update it when the user clicks the button.
For example:
class SampleApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( primarySwatch: Colors.blue, ), home: SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { SampleAppPage({Key key}) : super(key: key); @override _SampleAppPageState createState() => _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { // Default placeholder text String textToShow = "I Like Flutter"; void _updateText() { setState(() { // update the text textToShow = "Flutter is Awesome!"; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Sample App"), ), body: Center(child: Text(textToShow)), floatingActionButton: FloatingActionButton( onPressed: _updateText, tooltip: 'Update Text', child: Icon(Icons.update), ), ); } }
How do I lay out my widgets? Where is my Storyboard?
In iOS, you might use a Storyboard file to organize your views and set constraints, or you might set your constraints programmatically in your view controllers. In Flutter, declare your layout in code by composing a widget tree.
The following example shows how to display a simple widget with padding:
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Sample App"), ), body: Center( child: CupertinoButton( onPressed: () { setState(() { _pressedCount += 1; }); }, child: Text('Hello'), padding: EdgeInsets.only(left: 10.0, right: 10.0), ), ), ); }
How do I add or remove a component from my layout?
In iOS, you call addSubview()
on the parent, or removeFromSuperview()
on a child view to dynamically add or remove child views. In Flutter, because widgets are immutable there is no direct equivalent to addSubview()
. Instead, you can pass a function to the parent that returns a widget, and control that child’s creation with a boolean flag.
The following example shows how to toggle between two widgets when the user clicks the FloatingActionButton
:
class SampleApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( primarySwatch: Colors.blue, ), home: SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { SampleAppPage({Key key}) : super(key: key); @override _SampleAppPageState createState() => _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { // Default value for toggle bool toggle = true; void _toggle() { setState(() { toggle = !toggle; }); } _getToggleChild() { if (toggle) { return Text('Toggle One'); } else { return CupertinoButton( onPressed: () {}, child: Text('Toggle Two'), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Sample App"), ), body: Center( child: _getToggleChild(), ), floatingActionButton: FloatingActionButton( onPressed: _toggle, tooltip: 'Update Text', child: Icon(Icons.update), ), ); } }
This is a snippet of the content you can check the full details on
You can some realtime Flutter App live demo here
Flutter for Android developers
This document is meant for Android developers looking to apply their existing Android knowledge to build mobile apps with Flutter. If you understand the fundamentals of the Android framework then you can use this document as a jump start to Flutter development.
Your Android knowledge and skill set are highly valuable when building with Flutter, because Flutter relies on the mobile operating system for numerous capabilities and configurations. Flutter is a new way to build UIs for mobile, but it has a plugin system to communicate with Android (and iOS) for non-UI tasks. If you’re an expert with Android, you don’t have to relearn everything to use Flutter.
This document can be used as a cookbook by jumping around and finding questions that are most relevant to your needs.
Views
What is the equivalent of a View in Flutter?
How is react-style, or declarative , programming different than the traditional imperative style? For a comparison, see Introduction to declarative UI .
In Android, the View
is the foundation of everything that shows up on the screen. Buttons, toolbars, and inputs, everything is a View. In Flutter, the rough equivalent to a View
is a Widget
. Widgets don’t map exactly to Android views, but while you’re getting acquainted with how Flutter works you can think of them as “the way you declare and construct UI”.
However, these have a few differences to a View
. To start, widgets have a different lifespan: they are immutable and only exist until they need to be changed. Whenever widgets or their state change, Flutter’s framework creates a new tree of widget instances. In comparison, an Android view is drawn once and does not redraw until invalidate
is called.
Flutter’s widgets are lightweight, in part due to their immutability. Because they aren’t views themselves, and aren’t directly drawing anything, but rather are a description of the UI and its semantics that get “inflated” into actual view objects under the hood.
Flutter includes the Material Components library. These are widgets that implement the Material Design guidelines . Material Design is a flexible design system optimized for all platforms , including iOS.
But Flutter is flexible and expressive enough to implement any design language. For example, on iOS, you can use the Cupertino widgets to produce an interface that looks like Apple’s iOS design language .
How do I update widgets?
In Android, you update your views by directly mutating them. However, in Flutter, Widget
s are immutable and are not updated directly, instead you have to work with the widget’s state.
This is where the concept of Stateful and Stateless widgets comes from. A StatelessWidget
is just what it sounds like—a widget with no state information.
StatelessWidgets
are useful when the part of the user interface you are describing does not depend on anything other than the configuration information in the object.
For example, in Android, this is similar to placing an ImageView
with your logo. The logo is not going to change during runtime, so use a StatelessWidget
in Flutter.
If you want to dynamically change the UI based on data received after making an HTTP call or user interaction then you have to work with StatefulWidget
and tell the Flutter framework that the widget’s State
has been updated so it can update that widget.
The important thing to note here is at the core both stateless and stateful widgets behave the same. They rebuild every frame, the difference is the StatefulWidget
has a State
object that stores state data across frames and restores it.
If you are in doubt, then always remember this rule: if a widget changes (because of user interactions, for example) it’s stateful. However, if a widget reacts to change, the containing parent widget can still be stateless if it doesn’t itself react to change.
The following example shows how to use a StatelessWidget
. A common StatelessWidget
is the Text
widget. If you look at the implementation of the Text
widget you’ll find that it subclasses StatelessWidget
.
Text( 'I like Flutter!', style: TextStyle(fontWeight: FontWeight.bold), );
As you can see, the Text
Widget has no state information associated with it, it renders what is passed in its constructors and nothing more.
But, what if you want to make “I Like Flutter” change dynamically, for example when clicking a FloatingActionButton
?
To achieve this, wrap the Text
widget in a StatefulWidget
and update it when the user clicks the button.
For example:
import 'package:flutter/material.dart'; void main() { runApp(SampleApp()); } class SampleApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( primarySwatch: Colors.blue, ), home: SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { SampleAppPage({Key key}) : super(key: key); @override _SampleAppPageState createState() => _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { // Default placeholder text String textToShow = "I Like Flutter"; void _updateText() { setState(() { // update the text textToShow = "Flutter is Awesome!"; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Sample App"), ), body: Center(child: Text(textToShow)), floatingActionButton: FloatingActionButton( onPressed: _updateText, tooltip: 'Update Text', child: Icon(Icons.update), ), ); } }
How do I lay out my widgets? Where is my XML layout file?
In Android, you write layouts in XML, but in Flutter you write your layouts with a widget tree.
The following example shows how to display a simple widget with padding:
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Sample App"), ), body: Center( child: MaterialButton( onPressed: () {}, child: Text('Hello'), padding: EdgeInsets.only(left: 10.0, right: 10.0), ), ), ); }
How do I add or remove a component from my layout?
In Android, you call addChild()
or removeChild()
on a parent to dynamically add or remove child views. In Flutter, because widgets are immutable there is no direct equivalent to addChild()
. Instead, you can pass a function to the parent that returns a widget, and control that child’s creation with a boolean flag.
For example, here is how you can toggle between two widgets when you click on a FloatingActionButton
:
import 'package:flutter/material.dart'; void main() { runApp(SampleApp()); } class SampleApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( primarySwatch: Colors.blue, ), home: SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { SampleAppPage({Key key}) : super(key: key); @override _SampleAppPageState createState() => _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { // Default value for toggle bool toggle = true; void _toggle() { setState(() { toggle = !toggle; }); } _getToggleChild() { if (toggle) { return Text('Toggle One'); } else { return MaterialButton(onPressed: () {}, child: Text('Toggle Two')); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Sample App"), ), body: Center( child: _getToggleChild(), ), floatingActionButton: FloatingActionButton( onPressed: _toggle, tooltip: 'Update Text', child: Icon(Icons.update), ), ); } }
This is a snippet of the content you can check the full details on
You can some realtime Flutter App live demo here
Flutter for web developers
users who are familiar with the HTML and CSS syntax for arranging components of an application’s UI. It maps HTML/CSS code snippets to their Flutter/Dart code equivalents.
The examples assume:
- The HTML document starts with
<!DOCTYPE html>
, and the CSS box model for all HTML elements is set toborder-box
, for consistency with the Flutter model.
{ box-sizing: border-box; }
. In Flutter, the default styling of the “Lorem ipsum” text is defined by the bold24Roboto
variable as follows, to keep the syntax simple:
TextStyle bold24Roboto = TextStyle( color: Colors.white, fontSize: 24, fontWeight: FontWeight.w900, );
How is react-style, or declarative , programming different than the traditional imperative style? For a comparison, see Introduction to declarative UI .
Performing basic layout operations
The following examples show how to perform the most common UI layout tasks.
Styling and aligning text
Font style, size, and other text attributes that CSS handles with the font and color properties are individual properties of a TextStyle child of a Text widget.
In both HTML and Flutter, child elements or widgets are anchored at the top left, by default.
<div class="greybox"> Lorem ipsum </div> .greybox { background-color: #e0e0e0; /* grey 300 */ width: 320px; height: 240px; font: 900 24px Georgia; }var container = Container( // grey box child: Text( "Lorem ipsum", style: TextStyle( fontSize: 24, fontWeight: FontWeight.w900, fontFamily: "Georgia", ), ), width: 320, height: 240, color: Colors.grey[300], );
Setting background color
In Flutter, you set the background color using a Container ’s decoration
property.
The CSS examples use the hex color equivalents to the Material color palette.
<div class="greybox"> Lorem ipsum </div> .greybox { background-color: #e0e0e0; /* grey 300 */ width: 320px; height: 240px; font: 900 24px Roboto; }var container = Container( // grey box child: Text( "Lorem ipsum", style: bold24Roboto, ), width: 320, height: 240, decoration: BoxDecoration( color: Colors.grey[300], ), );
Centering components
A Center widget centers its child both horizontally and vertically.
To accomplish a similar effect in CSS, the parent element uses either a flex or table-cell display behavior. The examples on this page show the flex behavior.
<div class="greybox"> Lorem ipsum </div> .greybox { background-color: #e0e0e0; /* grey 300 */ width: 320px; height: 240px; font: 900 24px Roboto; display: flex; align-items: center; justify-content: center; }var container = Container( // grey box child: Center( child: Text( "Lorem ipsum", style: bold24Roboto, ), ), width: 320, height: 240, color: Colors.grey[300], );
Setting container width
To specify the width of a Container widget, use its width
property. This is a fixed width, unlike the CSS max-width property that adjusts the container width up to a maximum value. To mimic that effect in Flutter, use the constraints
property of the Container. Create a new BoxConstraints widget with a minWidth
or maxWidth
.
For nested Containers, if the parent’s width is less than the child’s width, the child Container sizes itself to match the parent.
<div class="greybox"> <div class="redbox"> Lorem ipsum </div> </div> .greybox { background-color: #e0e0e0; /* grey 300 */ width: 320px; height: 240px; font: 900 24px Roboto; display: flex; align-items: center; justify-content: center; } .redbox { background-color: #ef5350; /* red 400 */ padding: 16px; color: #ffffff; width: 100%; max-width: 240px; }var container = Container( // grey box child: Center( child: Container( // red box child: Text( "Lorem ipsum", style: bold24Roboto, ), decoration: BoxDecoration( color: Colors.red[400], ), padding: EdgeInsets.all(16), width: 240, //max-width is 240 ), ), width: 320, height: 240, color: Colors.grey[300], );
This is a snippet of the content you can check the full details on
You can some realtime Flutter App live demo here:
Flutter for React Native developers
React Native (RN) developers looking to apply their existing RN knowledge to build mobile apps with Flutter. If you understand the fundamentals of the RN framework then you can use this document as a way to get started learning Flutter development.
This document can be used as a cookbook by jumping around and finding questions that are most relevant to your needs.
Introduction to Dart for JavaScript Developers
Like React Native, Flutter uses reactive-style views. However, while RN transpiles to native widgets, Flutter compiles all the way to native code. Flutter controls each pixel on the screen, which avoids performance problems caused by the need for a JavaScript bridge.
Dart is an easy language to learn and offers the following features:
- Provides an open-source, scalable programming language for building web, server, and mobile apps.
- Provides an object-oriented, single inheritance language that uses a C-style syntax that is AOT-compiled into native.
- Transcompiles optionally into JavaScript.
- Supports interfaces and abstract classes.
A few examples of the differences between JavaScript and Dart are described below.
Entry point
JavaScript doesn’t have a pre-defined entry function — you define the entry point.
// JavaScript function startHere() { // Can be used as entry point }
In Dart, every app must have a top-level main()
function that serves as the entry point to the app.
// Dart main() { }
Printing to the console
To print to the console in Dart, use print()
.
// JavaScript console.log('Hello world!');// Dart print('Hello world!');
Variables
Dart is type safe — it uses a combination of static type checking and runtime checks to ensure that a variable’s value always matches the variable’s static type. Although types are mandatory, some type annotations are optional because Dart performs type inference.
Creating and assigning variables
In JavaScript, variables cannot be typed.
In Dart , variables must either be explicitly typed or the type system must infer the proper type automatically.
// JavaScript var name = 'JavaScript';// Dart String name = 'dart'; // Explicitly typed as a string. var otherName = 'Dart'; // Inferred string. // Both are acceptable in Dart.
Default value
In JavaScript, uninitialized variables are undefined
.
In Dart, uninitialized variables have an initial value of null
. Because numbers are objects in Dart, even uninitialized variables with numeric types have the value null
.
// JavaScript var name; // == undefined// Dart var name; // == null int x; // == null
Checking for null or zero
In JavaScript, values of 1 or any non-null objects are treated as true.
// JavaScript var myNull = null; if (!myNull) { console.log('null is treated as false'); } var zero = 0; if (!zero) { console.log('0 is treated as false'); }
In Dart, only the boolean value true
is treated as true.
// Dart var myNull = null; if (myNull == null) { print('use "== null" to check null'); } var zero = 0; if (zero == 0) { print('use "== 0" to check zero'); }
Functions
Dart and JavaScript functions are generally similar. The primary difference is the declaration.
// JavaScript function fn() { return true; }// Dart fn() { return true; } // can also be written as bool fn() { return true; }
This is a snippet of the content you can check the full details on
You can some realtime Flutter App live demo here
Flutter for Xamarin.Forms developers
Xamarin.Forms developers looking to apply their existing knowledge to build mobile apps with Flutter. If you understand the fundamentals of the Xamarin.Forms framework, then you can use this document as a jump start to Flutter development.
Your Android and iOS knowledge and skill set are valuable when building with Flutter, because Flutter relies on the native operating system configurations, similar to how you would configure your native Xamarin.Forms projects. The Flutter Frameworks is also similar to how you create a single UI, that is used on multiple platforms.
This document can be used as a cookbook by jumping around and finding questions that are most relevant to your needs.
Project setup
How does the app start?
For each platform in Xamarin.Forms, you call the LoadApplication
method, which creates a new application and starts your app.
LoadApplication(new App());
In Flutter, the default main entry point is main
where you load your Flutter app.
void main() { runApp(new MyApp()); }
In Xamarin.Forms, you assign a Page
to the MainPage
property in the Application
class.
public class App: Application { public App() { MainPage = new ContentPage() { new Label() { Text="Hello World", HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center } }; } }
In Flutter, “everything is a widget”, even the application itself. The following example shows MyApp
, a simple application Widget
.
class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new Center( child: Text("Hello World!", textDirection: TextDirection.ltr)); } }
How do you create a page?
Xamarin.Forms has many different types of pages; ContentPage
is the most common. In Flutter, you specify an application widget that holds your root page. You can use a MaterialApp widget, which supports Material Design , or you can use a CupertinoApp widget, which supports an iOS-style app, or you can use the lower level WidgetsApp , which you can customize in any way you want.
The following code defines the home page, a stateful widget. In Flutter, all widgets are immutable, but two types of widgets are supported: stateful and stateless. Examples of a stateless widget are titles, icons, or images.
The following example uses MaterialApp, which holds its root page in the home
property.
class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(title: 'Flutter Demo Home Page'), ); } }
From here, your actual first page is another Widget
, in which you create your state.
A stateful widget, such as MyHomePage below, consists of two parts. The first part, which is itself immutable, creates a State object that holds the state of the object. The State object persists over the life of the widget.
class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); }
The State
object implements the build()
method for the stateful widget.
When the state of the widget tree changes, call setState()
, which triggers a build of that portion of the UI. Make sure to call setState()
only when necessary, and only on the part of the widget tree that has changed, or it can result in poor UI performance.
class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( // Take the value from the MyHomePage object that was created by // the App.build method, and use it to set the appbar title. title: new Text(widget.title), ), body: new Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text( 'You have pushed the button this many times:', ), new Text( '$_counter', style: Theme.of(context).textTheme.display1, ), ], ), ), floatingActionButton: new FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: new Icon(Icons.add), ), ); } }
In Flutter, the UI (also known as widget tree), is immutable, meaning you can’t change its state once it’s built. You change fields in your State
class, then call setState()
to rebuild the entire widget tree again.
This way of generating UI is different than Xamarin.Forms, but there are many benefits to this approach.
Views
What is the equivalent of a Page or Element in Flutter?
How is react-style, or declarative , programming different than the traditional imperative style? For a comparison, see Introduction to declarative UI .
ContentPage
, TabbedPage
, MasterDetailPage
are all types of pages you might in a Xamarin.Forms application. These pages would then hold Element
s to display the various controls. In Xamarin.Forms an Entry
or Button
are examples of an Element
.
In Flutter, almost everything is a widget. A Page
, called a Route
in Flutter, is a widget. Buttons, progress bars, and animation controllers are all widgets. When building a route, you create a widget tree.
Flutter includes the Material Components library. These are widgets that implement the Material Design guidelines . Material Design is a flexible design system optimized for all platforms , including iOS.
But Flutter is flexible and expressive enough to implement any design language. For example, on iOS, you can use the Cupertino widgets to produce an interface that looks like Apple’s iOS design language .
How do I update widgets?
In Xamarin.Forms, each Page
or Element
is a stateful class, that has properties and methods. You update your Element
by updating a property, and this is propagated down to the native control.
In Flutter, Widget
s are immutable and you can’t directly update them by changing a property, instead you have to work with the widget’s state.
This is where the concept of Stateful vs Stateless widgets comes from. A StatelessWidget
is just what it sounds like—a widget with no state information.
StatelessWidgets
are useful when the part of the user interface you are describing does not depend on anything other than the configuration information in the object.
For example, in Xamarin.Forms, this is similar to placing an Image
with your logo. The logo is not going to change during runtime, so use a StatelessWidget
in Flutter.
If you want to dynamically change the UI based on data received after making an HTTP call or user interaction then you have to work with StatefulWidget
and tell the Flutter framework that the widget’s State
has been updated so it can update that widget.
The important thing to note here is at the core both stateless and stateful widgets behave the same. They rebuild every frame, the difference is the StatefulWidget
has a State
object that stores state data across frames and restores it.
If you are in doubt, then always remember this rule: if a widget changes (because of user interactions, for example) it’s stateful. However, if a widget reacts to change, the containing parent widget can still be stateless if it doesn’t itself react to change.
The following example shows how to use a StatelessWidget
. A common StatelessWidget
is the Text
widget. If you look at the implementation of the Text
widget you’ll find it subclasses StatelessWidget
.
new Text( 'I like Flutter!', style: new TextStyle(fontWeight: FontWeight.bold), );
As you can see, the Text
widget has no state information associated with it, it renders what is passed in its constructors and nothing more.
But, what if you want to make “I Like Flutter” change dynamically, for example when clicking a FloatingActionButton
?
To achieve this, wrap the Text
widget in a StatefulWidget
and update it when the user clicks the button, as shown in the following example:
import 'package:flutter/material.dart'; void main() { runApp(new SampleApp()); } class SampleApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( title: 'Sample App', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { SampleAppPage({Key key}) : super(key: key); @override _SampleAppPageState createState() => new _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { // Default placeholder text String textToShow = "I Like Flutter"; void _updateText() { setState(() { // Update the text textToShow = "Flutter is Awesome!"; }); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("Sample App"), ), body: new Center(child: new Text(textToShow)), floatingActionButton: new FloatingActionButton( onPressed: _updateText, tooltip: 'Update Text', child: new Icon(Icons.update), ), ); } }
How do I lay out my widgets? What is the equivalent of an XAML file?
In Xamarin.Forms, most developers write layouts in XAML, though sometimes in C#. In Flutter, you write your layouts with a widget tree in code.
The following example shows how to display a simple widget with padding:
@override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("Sample App"), ), body: new Center( child: new MaterialButton( onPressed: () {}, child: new Text('Hello'), padding: new EdgeInsets.only(left: 10.0, right: 10.0), ), ), ); }
How do I add or remove an Element from my layout?
In Xamarin.Forms, you had to remove or add an Element
in code. This involved either setting the Content
property or calling Add()
or Remove()
if it was a list.
In Flutter, because widgets are immutable there is no direct equivalent. Instead, you can pass a function to the parent that returns a widget, and control that child’s creation with a boolean flag.
The following example shows how to toggle between two widgets when the user clicks the FloatingActionButton
:
class SampleApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( title: 'Sample App', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { SampleAppPage({Key key}) : super(key: key); @override _SampleAppPageState createState() => new _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { // Default value for toggle bool toggle = true; void _toggle() { setState(() { toggle = !toggle; }); } _getToggleChild() { if (toggle) { return new Text('Toggle One'); } else { return new CupertinoButton( onPressed: () {}, child: new Text('Toggle Two'), ); } } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("Sample App"), ), body: new Center( child: _getToggleChild(), ), floatingActionButton: new FloatingActionButton( onPressed: _toggle, tooltip: 'Update Text', child: new Icon(Icons.update), ), ); } }
How do I animate a widget?
In Xamarin.Forms, you create simple animations using ViewExtensions that include methods such as FadeTo
and TranslateTo
. You would use these methods on a view to perform the required animations.
content_copy
<Image Source="{Binding MyImage}" x:Name="myImage" />
Then in code behind, or a behavior, this would fade in the image, over a 1 second period.
content_copy
myImage.FadeTo(0, 1000);
In Flutter, you animate widgets using the animation library by wrapping widgets inside an animated widget. Use an AnimationController
, which is an Animation<double>
that can pause, seek, stop and reverse the animation. It requires a Ticker
that signals when vsync happens, and produces a linear interpolation between 0 and 1 on each frame while it’s running. You then create one or more Animation
s and attach them to the controller.
For example, you might use CurvedAnimation
to implement an animation along an interpolated curve. In this sense, the controller is the “master” source of the animation progress and the CurvedAnimation
computes the curve that replaces the controller’s default linear motion. Like widgets, animations in Flutter work with composition.
When building the widget tree, you assign the Animation
to an animated property of a widget, such as the opacity of a FadeTransition
, and tell the controller to start the animation.
The following example shows how to write a FadeTransition
that fades the widget into a logo when you press the FloatingActionButton
:
import 'package:flutter/material.dart'; void main() { runApp(new FadeAppTest()); } class FadeAppTest extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( title: 'Fade Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyFadeTest(title: 'Fade Demo'), ); } } class MyFadeTest extends StatefulWidget { MyFadeTest({Key key, this.title}) : super(key: key); final String title; @override _MyFadeTest createState() => new _MyFadeTest(); } class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin { AnimationController controller; CurvedAnimation curve; @override void initState() { controller = new AnimationController(duration: const Duration(milliseconds: 2000), vsync: this); curve = new CurvedAnimation(parent: controller, curve: Curves.easeIn); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Center( child: new Container( child: new FadeTransition( opacity: curve, child: new FlutterLogo( size: 100.0, )))), floatingActionButton: new FloatingActionButton( tooltip: 'Fade', child: new Icon(Icons.brush), onPressed: () { controller.forward(); }, ), ); } }
For more information, see Animation & Motion widgets , the Animations tutorial , and the Animations overview .
This is a snippet of the content you can check the full details on
You can some realtime Flutter App live demo here
Now let’s build your application with Flutter and speed up your development process. It does not matter on which platforms you are coming, Now Flutter available for all major platforms development. The above documentation is a short snippet of all platforms provided by Flutter's official site. So you can check all elements on their documentation on flutter.dev
For more updates stay connected with usIonic Firebase App
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK