id
stringlengths 14
17
| text
stringlengths 23
1.11k
| source
stringlengths 35
114
|
---|---|---|
b16dc750a3a9-21 | Static data such as JSON files
Configuration files
Icons and images (JPEG, PNG, GIF, Animated GIF, WebP, Animated WebP, BMP,
and WBMP)
Flutter uses the pubspec.yaml file,
located at the root of your project, to
identify assets required by an app.
flutter
assets
assets/my_icon.png
assets/background.png
The assets subsection specifies files that should be included with the app.
Each asset is identified by an explicit path
relative to the pubspec.yaml file, where the asset file is located.
The order in which the assets are declared does not matter.
The actual directory used (assets in this case) does not matter.
However, while assets can be placed in any app directory, it’s a
best practice to place them in the assets directory. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-22 | During a build, Flutter places assets into a special archive
called the asset bundle, which apps read from at runtime.
When an asset’s path is specified in the assets’ section of pubspec.yaml,
the build process looks for any files
with the same name in adjacent subdirectories.
These files are also included in the asset bundle
along with the specified asset. Flutter uses asset variants
when choosing resolution-appropriate images for your app.
In React Native, you would add a static image by placing the image file
in a source code directory and referencing it.
Image
source
require
./my-icon.png
)}
In Flutter, add a static image to your app
using the Image.asset constructor in a widget’s build method.
For more information, see Adding Assets and Images in Flutter.
How do I load images over a network? | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-23 | How do I load images over a network?
In React Native, you would specify the uri in the
source prop of the Image component and also provide the
size if needed.
In Flutter, use the Image.network constructor to include
an image from a URL.
How do I install packages and package plugins?
Flutter supports using shared packages contributed by other developers to the
Flutter and Dart ecosystems. This allows you to quickly build your app without
having to develop everything from scratch. Packages that contain
platform-specific code are known as package plugins.
In React Native, you would use yarn add {package-name} or
npm install --save {package-name} to install packages
from the command line.
In Flutter, install a package using the following instructions: | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-24 | In Flutter, install a package using the following instructions:
Add the package name and version to the pubspec.yaml dependencies section.
The example below shows how to add the google_sign_in Dart package to the
pubspec.yaml file. Check your spaces when working in the YAML file because
white space matters!
dependencies
flutter
sdk
flutter
google_sign_in
^3.0.3
Install the package from the command line by using flutter pub get.
If using an IDE, it often runs flutter pub get for you, or it might
prompt you to do so.
Import the package into your app code as shown below:
For more information, see Using Packages and
Developing Packages & Plugins.
You can find many packages shared by Flutter developers in the
Flutter packages section of pub.dev.
Flutter widgets | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-25 | Flutter widgets
In Flutter, you build your UI out of widgets that describe what their view
should look like given their current configuration and state.
The Center widget is another example of how you can control the layout.
To center a widget, wrap it in a Center widget and then use layout
widgets for alignment, row, columns, and grids.
These layout widgets do not have a visual representation of their own.
Instead, their sole purpose is to control some aspect of another
widget’s layout. To understand why a widget renders in a
certain way, it’s often helpful to inspect the neighboring widgets.
For more information, see the Flutter Technical Overview.
For more information about the core widgets from the Widgets package,
see Flutter Basic Widgets,
the Flutter Widget Catalog,
or the Flutter Widget Index.
Views
What is the equivalent of the View container? | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-26 | Views
What is the equivalent of the View container?
In React Native, View is a container that supports layout with Flexbox,
style, touch handling, and accessibility controls.
Container,
Column,
Row, and
Center.
For more information, see the
Layout Widgets catalog.
What is the equivalent of FlatList or SectionList?
A List is a scrollable list of components arranged vertically.
In React Native, FlatList or SectionList are used to render simple or
sectioned lists.
// React Native
FlatList
data
{[
...
]}
renderItem
{({
item
})
=>
Text
item
key | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-27 | =>
Text
item
key
/Text>
/>
ListView is Flutter’s most commonly used scrolling widget.
The default constructor takes an explicit list of children.
ListView is most appropriate for a small number of widgets.
For a large or infinite list, use ListView.builder,
which builds its children on demand and only builds
those children that are visible.
To learn how to implement an infinite scrolling list, see the official
infinite_list sample.
How do I use a Canvas to draw or paint?
In React Native, canvas components aren’t present
so third party libraries like react-native-canvas are used.
// React Native
handleCanvas
canvas
=>
const
ctx
canvas
getContext
2d
);
ctx | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-28 | 2d
);
ctx
fillStyle
skyblue
ctx
beginPath
();
ctx
arc
75
75
50
Math
PI
);
ctx
fillRect
150
100
300
300
);
ctx
stroke
();
};
render
()
return
View
Canvas
ref
this
handleCanvas
/View
); | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-29 | handleCanvas
/View
);
In Flutter, you can use the CustomPaint
and CustomPainter classes to draw to the canvas.
Layouts
How do I use widgets to define layout properties?
In React Native, most of the layout can be done with the props
that are passed to a specific component.
For example, you could use the style prop on the View component
in order to specify the flexbox properties.
To arrange your components in a column, you would specify a prop such as:
flexDirection: 'column'.
// React Native
View
style
{{
flex
flexDirection
column
justifyContent
space-between
alignItems
center
}} | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-30 | alignItems
center
}}
In Flutter, the layout is primarily defined by widgets
specifically designed to provide layout,
combined with control widgets and their style properties.
For example, the Column and Row widgets
take an array of children and align them
vertically and horizontally respectively.
A Container widget takes a combination of
layout and styling properties, and a
Center widget centers its child widgets.
Flutter provides a variety of layout widgets in its core widget library.
For example, Padding, Align, and Stack.
For a complete list, see Layout Widgets.
How do I layer widgets?
In React Native, components can be layered using absolute positioning.
Flutter uses the Stack
widget to arrange children widgets in layers.
The widgets can entirely or partially overlap the base widget. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-31 | The Stack widget positions its children relative to the edges of its box.
This class is useful if you simply want to overlap several children widgets.
The previous example uses Stack to overlay a Container
(that displays its Text on a translucent black background)
on top of a CircleAvatar.
The Stack offsets the text using the alignment property
and Alignment coordinates.
For more information, see the Stack class documentation.
Styling
How do I style my components?
In React Native, inline styling and stylesheets.create
are used to style components.
// React Native
View
style
styles
container
Text
style
{{
fontSize
32
color
cyan
fontWeight
600
}} | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-32 | fontWeight
600
}}
This
is
sample
text
/Text
/View
const
styles
StyleSheet
create
({
container
flex
backgroundColor
#fff
alignItems
center
justifyContent
center
});
In Flutter, a Text widget can take a TextStyle class
for its style property. If you want to use the same text
style in multiple places, you can create a
TextStyle class and use it for multiple Text widgets.
How do I use Icons and Colors?
React Native doesn’t include support for icons
so third party libraries are used. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-33 | React Native doesn’t include support for icons
so third party libraries are used.
In Flutter, importing the Material library also pulls in the
rich set of Material icons and colors.
When using the Icons class,
make sure to set uses-material-design: true in
the project’s pubspec.yaml file.
This ensures that the MaterialIcons font,
which displays the icons, is included in your app.
In general, if you intend to use the Material library,
you should include this line.
name
my_awesome_application
flutter
uses-material-design
true
Flutter’s Cupertino (iOS-style) package provides high
fidelity widgets for the current iOS design language.
To use the CupertinoIcons font,
add a dependency for cupertino_icons in your project’s
pubspec.yaml file.
name
my_awesome_application | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-34 | name
my_awesome_application
dependencies
cupertino_icons
^0.1.0
To globally customize the colors and styles of components,
use ThemeData to specify default colors
for various aspects of the theme.
Set the theme property in MaterialApp to the ThemeData object.
The Colors class provides colors
from the Material Design color palette.
The following example sets the primary swatch to blue
and the text selection to red.
How do I add style themes?
In React Native, common themes are defined for
components in stylesheets and then used in components.
In Flutter, create uniform styling for almost everything
by defining the styling in the ThemeData
class and passing it to the theme property in the
MaterialApp widget.
Theme widget takes a
State management | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-35 | Theme widget takes a
State management
State is information that can be read synchronously
when a widget is built or information
that might change during the lifetime of a widget.
To manage app state in Flutter,
use a StatefulWidget paired with a State object.
For more information on ways to approach managing state in Flutter,
see State management.
The StatelessWidget
A StatelessWidget in Flutter is a widget
that doesn’t require a state change—
it has no internal state to manage.
Stateless widgets 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 itself and the
BuildContext in which the widget is inflated.
AboutDialog, CircleAvatar, and Text are examples
of stateless widgets that subclass StatelessWidget. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-36 | The previous example uses the constructor of the MyStatelessWidget
class to pass the text, which is marked as final.
This class extends StatelessWidget—it contains immutable data.
The build method of a stateless widget is typically called
in only three situations:
When the widget is inserted into a tree
When the widget’s parent changes its configuration
When an InheritedWidget it depends on, changes
The StatefulWidget
A StatefulWidget is a widget that changes state.
Use the setState method to manage the
state changes for a StatefulWidget.
A call to setState() tells the Flutter
framework that something has changed in a state,
which causes an app to rerun the build() method
so that the app can reflect the change. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-37 | State is information that can be read synchronously when a widget
is built and might change during the lifetime of the widget.
It’s the responsibility of the widget implementer to ensure that
the state object is promptly notified when the state changes.
Use StatefulWidget when a widget can change dynamically.
For example, the state of the widget changes by typing into a form,
or moving a slider.
Or, it can change over time—perhaps a data feed updates the UI.
Checkbox,
Radio,
Slider,
InkWell,
Form, and
TextField
are examples of stateful widgets that subclass
StatefulWidget.
The following example declares a StatefulWidget
that requires a createState() method.
This method creates the state object that manages the widget’s state,
_MyStatefulWidgetState. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-38 | The following state class, _MyStatefulWidgetState,
implements the build() method for the widget.
When the state changes, for example, when the user toggles
the button, setState() is called with the new toggle value.
This causes the framework to rebuild this widget in the UI.
What are the StatefulWidget and StatelessWidget best practices?
Here are a few things to consider when designing your widget.
Determine whether a widget should be
a StatefulWidget or a StatelessWidget.
In Flutter, widgets are either Stateful or Stateless—depending on whether
they depend on a state change.
If a widget changes—the user interacts with it or
a data feed interrupts the UI, then it’s Stateful.
If a widget is final or immutable, then it’s Stateless.
Determine which object manages the widget’s state (for a StatefulWidget). | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-39 | Determine which object manages the widget’s state (for a StatefulWidget).
In Flutter, there are three primary ways to manage state:
The widget manages its own state
The parent widget manages the widget’s state
A mix-and-match approach
When deciding which approach to use, consider the following principles:
If the state in question is user data,
for example the checked or unchecked mode of a checkbox,
or the position of a slider, then the state is best managed
by the parent widget.
If the state in question is aesthetic, for example an animation,
then the widget itself best manages the state.
When in doubt, let the parent widget manage the child widget’s state.
Subclass StatefulWidget and State.
Add the StatefulWidget into the widget tree.
Add your custom StatefulWidget to the widget tree
in the app’s build method. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-40 | Add your custom StatefulWidget to the widget tree
in the app’s build method.
Props
In React Native, most components can be customized when they are
created with different parameters or properties, called props.
These parameters can be used in a child component using this.props.
// React Native
class
CustomCard
extends
React
Component
render
()
return
View
Text
Card
this
props
index
/Text
Button
title
Press
onPress
{()
=>
this
props
onPress
this
props
index | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-41 | this
props
index
)}
/View
);
class
App
extends
React
Component
onPress
index
=>
console
log
Card
index
);
};
render
()
return
View
FlatList
data
{[
...
]}
renderItem
{({
item
})
=>
CustomCard
onPress
this
onPress
index
item | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-42 | onPress
index
item
key
)}
/View
);
In Flutter, you assign a local variable or function marked
final with the property received in the parameterized constructor.
Local storage
If you don’t need to store a lot of data, and it doesn’t require
structure, you can use shared_preferences which allows you to
read and write persistent key-value pairs of primitive data
types: booleans, floats, ints, longs, and strings.
How do I store persistent key-value pairs that are global to the app?
In React Native, you use the setItem and getItem functions
of the AsyncStorage component to store and retrieve data
that is persistent and global to the app.
// React Native
await
AsyncStorage
setItem
counterkey
json | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-43 | setItem
counterkey
json
stringify
++
this
state
counter
));
AsyncStorage
getItem
counterkey
).
then
value
=>
if
value
!=
null
this
setState
({
counter
value
});
});
shared_preferences plugin to
store and retrieve key-value data that is persistent and global
to the app. The
dependencies
flutter
sdk
flutter
shared_preferences
^2.0.13
Routing | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-44 | ^2.0.13
Routing
Most apps contain several screens for displaying different
types of information. For example, you might have a product
screen that displays images where users could tap on a product
image to get more information about the product on a new screen.
In Android, new screens are new Activities.
In iOS, new screens are new ViewControllers. In Flutter,
screens are just Widgets! And to navigate to new
screens in Flutter, use the Navigator widget.
How do I navigate between screens?
In React Native, there are three main navigators:
StackNavigator, TabNavigator, and DrawerNavigator.
Each provides a way to configure and define the screens.
// React Native
const
MyApp
TabNavigator
Home
screen
HomeScreen
},
Notifications
screen | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-45 | },
Notifications
screen
tabNavScreen
},
tabBarOptions
activeTintColor
#e91e63
);
const
SimpleApp
StackNavigator
({
Home
screen
MyApp
},
stackScreen
screen
StackScreen
});
export
default
MyApp1
DrawerNavigator
({
Home
screen
SimpleApp
},
Screen2
screen
drawerScreen
})); | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-46 | screen
drawerScreen
}));
In Flutter, there are two main widgets used to navigate between screens:
A Route is an abstraction for an app screen or page.
A Navigator is a widget that manages routes.
Navigator.push and
Navigator.pop.
A list of routes might be specified in the
MaterialApp widget,
or they might be built on the fly, for example, in hero animations.
The following example specifies named routes in the
Note:
Named routes are no longer recommended for most
applications. For more information, see
Limitations in the navigation overview page.
To navigate to a named route, the Navigator.of()
method is used to specify the BuildContext
(a handle to the location of a widget in the widget tree).
The name of the route is passed to the pushNamed function to
navigate to the specified route. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-47 | You can also use the push method of Navigator which
adds the given Route to the history of the
navigator that most tightly encloses the given BuildContext,
and transitions to it. In the following example,
the MaterialPageRoute widget is a modal route that
replaces the entire screen with a platform-adaptive
transition. It takes a WidgetBuilder as a required parameter.
How do I use tab navigation and drawer navigation?
In Material Design apps, there are two primary options
for Flutter navigation: tabs and drawers.
When there is insufficient space to support tabs, drawers
provide a good alternative.
Tab navigation
In React Native, createBottomTabNavigator
and TabNavigation are used to
show tabs and for tab navigation.
// React Native
import
createBottomTabNavigator
from
react-navigation
const
MyApp
TabNavigator | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-48 | const
MyApp
TabNavigator
Home
screen
HomeScreen
},
Notifications
screen
tabNavScreen
},
tabBarOptions
activeTintColor
#e91e63
);
Flutter provides several specialized widgets for drawer and
tab navigation:
TabController
Coordinates the tab selection between a TabBar
and a TabBarView.
TabBar
Displays a horizontal row of tabs.
Tab
Creates a material design TabBar tab.
TabBarView
Displays the widget that corresponds to the currently selected tab.
TickerProvider is an interface implemented
by classes that can vend | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-49 | TickerProvider is an interface implemented
by classes that can vend
Ticker objects.
Tickers can be used by any object that must be notified whenever a
frame triggers, but they’re most commonly used indirectly via an
AnimationController.
TickerProviderStateMixin
or
SingleTickerProviderStateMixin
classes to obtain a suitable
Scaffold widget wraps a new
Drawer navigation
In React Native, import the needed react-navigation packages and then use
createDrawerNavigator and DrawerNavigation.
// React Native
export
default
MyApp1
DrawerNavigator
({
Home
screen
SimpleApp
},
Screen2
screen
drawerScreen
})); | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-50 | screen
drawerScreen
}));
Material Design guidelines. It also supports
special Material Design components,
such as
ElevatedButton, a
Text widget,
or a list of items to display as the child to the
ListTile
widget provides the navigation on tap.
Gesture detection and touch event handling
To listen for and respond to gestures,
Flutter supports taps, drags, and scaling.
The gesture system in Flutter has two separate layers.
The first layer includes raw pointer events,
which describe the location and movement of pointers,
(such as touches, mice, and styli movements), across the screen.
The second layer includes gestures,
which describe semantic actions
that consist of one or more pointer movements.
How do I add a click or press listeners to a widget?
In React Native, listeners are added to components
using PanResponder or the Touchable components. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-51 | // React Native
TouchableOpacity
onPress
{()
=>
console
log
Press
);
}}
onLongPress
{()
=>
console
log
Long Press
);
}}
Text
Tap
or
Long
Press
/Text
/TouchableOpacity
For more complex gestures and combining several touches into
a single gesture, PanResponder is used.
// React Native
class
App
extends
Component
componentWillMount
()
this | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-52 | componentWillMount
()
this
_panResponder
PanResponder
create
({
onMoveShouldSetPanResponder
event
gestureState
=>
!!
getDirection
gestureState
),
onPanResponderMove
event
gestureState
=>
true
onPanResponderRelease
event
gestureState
=>
const
drag
getDirection
gestureState
);
},
onPanResponderTerminationRequest
event
gestureState
=>
true
}); | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-53 | =>
true
});
render
()
return
View
style
styles
container
{...
this
_panResponder
panHandlers
View
style
styles
center
Text
Swipe
Horizontally
or
Vertically
/Text
/View
/View
);
In Flutter, to add a click (or press) listener to a widget,
use a button or a touchable widget that has an onPress: field.
Or, add gesture detection to any widget by wrapping it
in a GestureDetector. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-54 | For more information, including a list of
Flutter GestureDetector callbacks,
see the GestureDetector class.
Making HTTP network requests
Fetching data from the internet is common for most apps. And in Flutter,
the http package provides the simplest way to fetch data from the internet.
How do I fetch data from API calls?
React Native provides the Fetch API for networking—you make a fetch request
and then receive the response to get the data.
// React Native
_getIPAddress
()
=>
fetch
https://httpbin.org/ip
then
response
=>
response
json
())
then
responseJson
=>
this
setState
({ | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-55 | this
setState
({
_ipAddress
responseJson
origin
});
})
catch
error
=>
console
error
error
);
});
};
Flutter uses the http package. To install the http package,
add it to the dependencies’ section of our pubspec.yaml.
dependencies
flutter
sdk
flutter
http
<latest_version>
Flutter uses the dart:io core HTTP support client.
To create an HTTP Client, import dart:io.
The client supports the following HTTP operations:
GET, POST, PUT, and DELETE.
Form input | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-56 | Form input
Text fields allow users to type text into your app so they can be
used to build forms, messaging apps, search experiences, and more.
Flutter provides two core text field widgets:
TextField and TextFormField.
How do I use text field widgets?
In React Native, to enter text you use a TextInput component to show a text
input box and then use the callback to store the value in a variable.
// React Native
TextInput
placeholder
Enter your Password
onChangeText
password
=>
this
setState
({
password
})}
Button
title
Submit
onPress
this
validate | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-57 | onPress
this
validate
In Flutter, use the TextEditingController
class to manage a TextField widget.
Whenever the text field is modified,
the controller notifies its listeners.
Listeners read the text and selection properties to
learn what the user typed into the field.
You can access the text in TextField
by the text property of the controller.
In this example, when a user clicks on the submit button an alert dialog
displays the current text entered in the text field.
This is achieved using an AlertDialog
widget that displays the alert message, and the text from
the TextField is accessed by the text property of the
TextEditingController.
How do I use Form widgets?
Form widget where
TextFormField widgets along with the submit
button are passed as children.
The
onSaved that takes a callback and executes
when the form is saved. A | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-58 | onSaved that takes a callback and executes
when the form is saved. A
The following example shows how Form.save() and formKey
(which is a GlobalKey), are used to save the form on submit.
Platform-specific code
When building a cross-platform app, you want to re-use as much code as
possible across platforms. However, scenarios might arise where it
makes sense for the code to be different depending on the OS.
This requires a separate implementation by declaring a specific platform.
In React Native, the following implementation would be used:
// React Native
if
Platform
OS
===
ios
return
iOS
else
if
Platform
OS
===
android
return
android
else
return | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-59 | return
android
else
return
not recognised
In Flutter, use the following implementation:
Debugging
What tools can I use to debug my app in Flutter?
Use the DevTools suite for debugging Flutter or Dart apps.
DevTools includes support for profiling, examining the heap,
inspecting the widget tree, logging diagnostics, debugging,
observing executed lines of code, debugging memory leaks and memory
fragmentation. For more information, see the
DevTools documentation.
If you’re using an IDE,
you can debug your application using the IDE’s debugger.
How do I perform a hot reload? | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-60 | How do I perform a hot reload?
Flutter’s Stateful Hot Reload feature helps you quickly and easily experiment,
build UIs, add features, and fix bugs. Instead of recompiling your app
every time you make a change, you can hot reload your app instantly.
The app is updated to reflect your change,
and the current state of the app is preserved.
In React Native,
the shortcut is ⌘R for the iOS Simulator and tapping R twice on
Android emulators.
In Flutter, If you are using IntelliJ IDE or Android Studio,
you can select Save All (⌘s/ctrl-s), or you can click the
Hot Reload button on the toolbar. If you
are running the app at the command line using flutter run,
type r in the Terminal window.
You can also perform a full restart by typing R in the
Terminal window.
How do I access the in-app developer menu? | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-61 | How do I access the in-app developer menu?
In React Native, the developer menu can be accessed by shaking your device: ⌘D
for the iOS Simulator or ⌘M for Android emulator.
In Flutter, if you are using an IDE, you can use the IDE tools. If you start
your application using flutter run you can also access the menu by typing h
in the terminal window, or type the following shortcuts:
Widget hierarchy of the app
debugDumpApp()
Rendering tree of the app
debugDumpRenderTree()
Layers
debugDumpLayerTree()
Accessibility
S (traversal order) orU (inverse hit test order)
debugDumpSemantics()
To toggle the widget inspector
WidgetsApp. showWidgetInspectorOverride
To toggle the display of construction lines | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-62 | To toggle the display of construction lines
debugPaintSizeEnabled
To simulate different operating systems
defaultTargetPlatform
To display the performance overlay
WidgetsApp. showPerformanceOverlay
To save a screenshot to flutter. png
To quit
Animation
Well-designed animation makes a UI feel intuitive,
contributes to the look and feel of a polished app,
and improves the user experience.
Flutter’s animation support makes it easy
to implement simple and complex animations.
The Flutter SDK includes many Material Design widgets
that include standard motion effects,
and you can easily customize these effects
to personalize your app.
In React Native, Animated APIs are used to create animations. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-63 | In React Native, Animated APIs are used to create animations.
In Flutter, use the Animation
class and the AnimationController class.
Animation is an abstract class that understands its
current value and its state (completed or dismissed).
The AnimationController class lets you
play an animation forward or in reverse,
or stop animation and set the animation
to a specific value to customize the motion.
How do I add a simple fade-in animation?
In the React Native example below, an animated component,
FadeInView is created using the Animated API.
The initial opacity state, final state, and the
duration over which the transition occurs are defined.
The animation component is added inside the Animated component,
the opacity state fadeAnim is mapped
to the opacity of the Text component that we want to animate,
and then, start() is called to start the animation.
// React Native
class
FadeInView
extends
React
Component | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-64 | extends
React
Component
state
fadeAnim
new
Animated
Value
// Initial value for opacity: 0
};
componentDidMount
()
Animated
timing
this
state
fadeAnim
toValue
duration
10000
}).
start
();
render
()
return
Animated
View
style
{{...
this
props
style
opacity
this
state
fadeAnim
}} | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-65 | state
fadeAnim
}}
this
props
children
/Animated.View
);
...
FadeInView
Text
Fading
in
/Text
/FadeInView
...
To create the same animation in Flutter, create an
AnimationController object named controller
and specify the duration. By default, an AnimationController
linearly produces values that range from 0.0 to 1.0,
during a given duration. The animation controller generates a new value
whenever the device running your app is ready to display a new frame.
Typically, this rate is around 60 values per second. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-66 | A Tween describes the interpolation between a
beginning and ending value or the mapping from an input
range to an output range. To use a Tween object
with an animation, call the Tween object’s animate()
method and pass it the Animation object that you want to modify.
For this example, a FadeTransition
widget is used and the opacity property is
mapped to the animation object.
To start the animation, use controller.forward().
Other operations can also be performed using the
controller such as fling() or repeat().
For this example, the FlutterLogo
widget is used inside the FadeTransition widget.
How do I add swipe animation to cards?
In React Native, either the PanResponder or
third-party libraries are used for swipe animation.
In Flutter, to add a swipe animation, use the
Dismissible widget and nest the child widgets.
React Native and Flutter widget equivalent components | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-67 | React Native and Flutter widget equivalent components
The following table lists commonly-used React Native
components mapped to the corresponding Flutter widget
and common widget properties.
Button
ElevatedButton
A basic raised button.
onPressed [required]
The callback when the button is tapped or otherwise activated.
Child
The button’s label.
Button
TextButton
A basic flat button.
onPressed [required]
The callback when the button is tapped or otherwise activated.
Child
The button’s label.
ScrollView
ListView
A scrollable list of widgets arranged linearly.
children
( <Widget> [ ]) List of child widgets to display.
controller | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-68 | controller
[ ScrollController ] An object that can be used to control a scrollable widget.
itemExtent
[ double ] If non-null, forces the children to have the given extent in the scroll direction.
scroll Direction
[ Axis ] The axis along which the scroll view scrolls.
FlatList
ListView.builder
The constructor for a linear array of widgets that are created on demand.
itemBuilder [required]
[IndexedWidgetBuilder] helps in building the children on demand. This callback is called only with indices greater than or equal to zero and less than the itemCount.
itemCount
[ int ] improves the ability of the ListView to estimate the maximum scroll extent.
Image
Image
A widget that displays an image.
image [required]
The image to display.
Image. asset | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-69 | The image to display.
Image. asset
Several constructors are provided for the various ways that an image can be specified.
width, height, color, alignment
The style and layout for the image.
fit
Inscribing the image into the space allocated during layout.
Modal
ModalRoute
A route that blocks interaction with previous routes.
animation
The animation that drives the route’s transition and the previous route’s forward transition.
ActivityIndicator
CircularProgressIndicator
A widget that shows progress along a circle.
strokeWidth
The width of the line used to draw the circle.
backgroundColor
The progress indicator’s background color. The current theme’s ThemeData.backgroundColor by default.
ActivityIndicator
LinearProgressIndicator | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-70 | ActivityIndicator
LinearProgressIndicator
A widget that shows progress along a line.
value
The value of this progress indicator.
RefreshControl
RefreshIndicator
A widget that supports the Material “swipe to refresh” idiom.
color
The progress indicator’s foreground color.
onRefresh
A function that’s called when a user drags the refresh indicator far enough to demonstrate that they want the app to refresh.
View
Container
A widget that surrounds a child widget.
View
Column
A widget that displays its children in a vertical array.
View
Row
A widget that displays its children in a horizontal array.
View
Center
A widget that centers its child within itself. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-71 | Center
A widget that centers its child within itself.
View
Padding
A widget that insets its child by the given padding.
padding [required]
[ EdgeInsets ] The amount of space to inset the child.
TouchableOpacity
GestureDetector
A widget that detects gestures.
onTap
A callback when a tap occurs.
onDoubleTap
A callback when a tap occurs at the same location twice in quick succession.
TextInput
TextInput
The interface to the system’s text input control.
controller
[ TextEditingController ] used to access and modify text.
Text
Text
The Text widget that displays a string of text with a single style.
data | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
b16dc750a3a9-72 | data
[ String ] The text to display.
textDirection
[ TextAlign ] The direction in which the text flows.
Switch
Switch
A material design switch.
value [required]
[ boolean ] Whether this switch is on or off.
onChanged [required]
[ callback ] Called when the user toggles the switch on or off.
Slider
Slider
Used to select from a range of values.
value [required]
[ double ] The current value of the slider.
onChanged [required]
Called when the user selects a new value for the slider. | https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html |
7e4ec76982c4-0 | Flutter for SwiftUI Developers
Overview
Views vs. Widgets
Layout process
Design system
UI Basics
Getting started
Adding Buttons
Aligning components horizontally
Aligning components vertically
Displaying a list view
Displaying a grid
Creating a scroll view
Responsive and adaptive design
Managing state
Animations
Implicit Animation
Explicit Animation
Drawing on the Screen
Navigation
Navigating between pages
Manually pop back
Navigating to another app
Themes, styles, and media
Using dark mode
Styling text
Styling buttons
Using custom fonts
Bundling images in apps
Bundling videos in apps
SwiftUI developers who want to write mobile apps using Flutter
should review this guide.
It explains how to apply existing SwiftUI knowledge to Flutter. | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-1 | Note:
If you instead have experience building apps for iOS with UIKit,
see Flutter for UIKit developers.
Flutter is a framework for building cross-platform applications
that uses the Dart programming language.
To understand some differences between programming with Dart
and programming with Swift, see Learning Dart as a Swift Developer
and Flutter concurrency for Swift developers.
Your SwiftUI knowledge and experience
are highly valuable when building with Flutter.
Flutter also makes a number of adaptations
to app behavior when running on iOS and macOS.
To learn how, see Platform adaptations.
To integrate Flutter code into an existing iOS app,
check out Add Flutter to existing app.
This document can be used as a cookbook by jumping around
and finding questions that are most relevant to your needs.
This guide embeds sample code.
You can test full working examples on DartPad or view them on GitHub.
Overview | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-2 | Overview
Flutter and SwiftUI code describes how the UI looks and works.
Developers call this type of code a declarative framework.
Views vs. Widgets
SwiftUI represents UI components as views.
You configure views using modifiers.
Text
"Hello, World!"
// <-- This is a View
padding
10
// <-- This is a modifier of that View
Flutter represents UI components as widgets.
Both views and widgets only exist until they need to be changed.
These languages call this property immutability.
SwiftUI represents a UI component property as a View modifier.
By contrast, Flutter uses widgets for both UI components and
their properties.
Padding
// <-- This is a Widget
padding:
EdgeInsets
all | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-3 | padding:
EdgeInsets
all
10.0
),
// <-- So is this
child:
Text
"Hello, World!"
),
// <-- This, too
)));
To compose layouts, both SwiftUI and Flutter nest UI components
within one another.
SwiftUI nests Views while Flutter nests Widgets.
Layout process
SwiftUI lays out views using the following process:
The parent view proposes a size to its child view.
All subsequent child views:
propose a size to their child’s view
ask that child what size it wants
Each parent view renders its child view at the returned size.
Flutter differs somewhat with its process: | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-4 | Flutter differs somewhat with its process:
The parent widget passes constraints down to its children.
Constraints include minimum and maximum values for height and width.
The child tries to decide its size. It repeats the same process with its own list of children:
It informs its child of the child’s constraints.
It asks its child what size it wishes to be.
The parent lays out the child.
If the requested size fits in the constraints,
the parent uses that size.
If the requested size doesn’t fit in the constraints,
the parent limits the height, width, or both to fit in
its constraints.
Flutter differs from SwiftUI because the parent component can override
the child’s desired size. The widget cannot have any size it wants.
It also cannot know or decide its position on screen as its parent
makes that decision. | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-5 | To force a child widget to render at a specific size,
the parent must set tight constraints.
A constraint becomes tight when its constraint’s minimum size value
equals its maximum size value.
In SwiftUI, views may expand to the available space or
limit their size to that of its content.
Flutter widgets behave in similar manner.
However, in Flutter parent widgets can offer unbounded constraints.
Unbounded constraints set their maximum values to infinity.
UnboundedBox
child:
Container
width:
double
infinity
height:
double
infinity
color:
red
),
If the child expands and it has unbounded constraints,
Flutter returns an overflow warning:
UnconstrainedBox
child:
Container
color:
red | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-6 | Container
color:
red
width:
4000
height:
50
),
To learn how constraints work in Flutter,
see Understanding constraints.
Design system
Because Flutter targets multiple platforms, your app doesn’t need
to conform to any design system.
Though this guide features Material widgets,
your Flutter app can use many different design systems:
Custom Material widgets
Community built widgets
Your own custom widgets
Cupertino widgets that follow Apple’s Human Interface Guidelines
If you’re looking for a great reference app that features a
custom design system, check out Wonderous.
UI Basics | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-7 | UI Basics
This section covers the basics of UI development in
Flutter and how it compares to SwiftUI.
This includes how to start developing your app, display static text,
create buttons, react to on-press events, display lists, grids, and more.
Getting started
In SwiftUI, you use App to start your app.
@main
struct
MyApp
App
var
body
some
Scene
WindowGroup
HomePage
()
Another common SwiftUI practice places the app body within a struct
that conforms to the View protocol as follows:
struct
HomePage
View
var
body
some
View
Text
"Hello, World!" | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-8 | View
Text
"Hello, World!"
To start your Flutter app, pass in an instance of your app to
the runApp function.
Test in DartPad
View on GitHub
App is a widget. The build method describes the part of the
user interface it represents.
It’s common to begin your app with a WidgetApp class,
like CupertinoApp.
Test in DartPad
View on GitHub
The widget used in HomePage might begin with the Scaffold class.
Scaffold implements a basic layout structure for an app.
Test in DartPad
View on GitHub | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-9 | Test in DartPad
View on GitHub
Note how Flutter uses the Center widget.
SwiftUI renders a view’s contents in its center by default.
That’s not always the case with Flutter.
Scaffold doesn’t render its body widget at the center of the screen.
To center the text, wrap it in a Center widget.
To learn about different widgets and their default behaviors, check out
the Widget catalog.
Adding Buttons
In SwiftUI, you use the Button struct to create a button.
Button
"Do something"
// this closure gets called when your
// button is tapped
To achieve the same result in Flutter,
use the CupertinoButton class:
Test in DartPad
View on GitHub | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-10 | Test in DartPad
View on GitHub
Flutter gives you access to a variety of buttons with predefined styles.
The CupertinoButton class comes from the Cupertino library.
Widgets in the Cupertino library use Apple’s design system.
Aligning components horizontally
In SwiftUI, stack views play a big part in designing your layouts.
Two separate structures allow you to create stacks:
HStack for horizontal stack views
VStack for vertical stack views
The following SwiftUI view adds a globe image and
text to a horizontal stack view:
HStack
Image
systemName
"globe"
Text
"Hello, world!"
Flutter uses Row rather than HStack:
Test in DartPad
View on GitHub
Aligning components vertically | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-11 | View on GitHub
Aligning components vertically
The following examples build on those in the previous section.
In SwiftUI, you use VStack to arrange the components into a
vertical pillar.
VStack
Image
systemName
"globe"
Text
"Hello, world!"
Flutter uses the same Dart code from the previous example,
except it swaps Column for Row:
Test in DartPad
View on GitHub
Displaying a list view
In SwiftUI, you use the List base component to display sequences
of items.
To display a sequence of model objects, make sure that the user can
identify your model objects.
To make an object identifiable, use the Identifiable protocol.
struct
Person
Identifiable
var
name | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-12 | Identifiable
var
name
String
var
persons
Person
name
"Person 1"
),
Person
name
"Person 2"
),
Person
name
"Person 3"
),
struct
ListWithPersons
View
let
persons
Person
var
body
some
View
List
ForEach
persons
person
in
Text
person
name | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-13 | in
Text
person
name
This resembles how Flutter prefers to build its list widgets.
Flutter doesn’t need the list items to be identifiable.
You set the number of items to display then build a widget for each item.
Test in DartPad
View on GitHub
Flutter has some caveats for lists:
The ListView widget has a builder method.
This works like the ForEach within SwiftUI’s List struct.
The itemCount parameter of the ListView sets how many items
the ListView displays.
The itemBuilder has an index parameter that will be between zero
and one less than itemCount.
The previous example returned a ListTile widget for each item.
The ListTile widget includes properties like height and font-size.
These properties help build a list. However, Flutter allows you to return
almost any widget that represents your data.
Displaying a grid | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-14 | Displaying a grid
When constructing non-conditional grids in SwiftUI,
you use Grid with GridRow.
Grid
GridRow
Text
"Row 1"
Image
systemName
"square.and.arrow.down"
Image
systemName
"square.and.arrow.up"
GridRow
Text
"Row 2"
Image
systemName
"square.and.arrow.down"
Image
systemName
"square.and.arrow.up"
To display grids in Flutter, use the GridView widget.
This widget has various constructors. Each constructor has
a similar goal, but uses different input parameters.
The following example uses the .builder() initializer: | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-15 | Test in DartPad
View on GitHub
The SliverGridDelegateWithFixedCrossAxisCount delegate determines
various parameters that the grid uses to lay out its components.
This includes crossAxisCount that dictates the number of items
displayed on each row.
How SwiftUI’s Grid and Flutter’s GridView differ in that Grid
requires GridRow. GridView uses the delegate to decide how the
grid should lay out its components.
Creating a scroll view
In SwiftUI, you use ScrollView to create custom scrolling
components.
The following example displays a series of PersonView instances
in a scrollable fashion.
ScrollView
VStack
alignment
leading
ForEach
persons
person
in
PersonView
person
person | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-16 | PersonView
person
person
To create a scrolling view, Flutter uses SingleChildScrollView.
In the following example, the function mockPerson mocks instances
of the Person class to create the custom PersonView widget.
Test in DartPad
View on GitHub
Responsive and adaptive design
In SwiftUI, you use GeometryReader to create relative view sizes.
For example, you could:
Multiply geometry.size.width by some factor to set the width.
Use GeometryReader as a breakpoint to change the design of your app.
You can also see if the size class has .regular or .compact
using horizontalSizeClass.
To create relative views in Flutter, you can use one of two options:
Get the BoxConstraints object in the LayoutBuilder class. | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-17 | Get the BoxConstraints object in the LayoutBuilder class.
Use the MediaQuery.of() in your build functions
to get the size and orientation of your current app.
To learn more, check out Creating responsive and adaptive apps.
Managing state
In SwiftUI, you use the @State property wrapper to represent the
internal state of a SwiftUI view.
struct
ContentView
View
@State
private
var
counter
var
body
some
View
VStack
Button
"+"
counter
+=
Text
String
counter
))
}}
SwiftUI also includes several options for more complex state
management such as the ObservableObject protocol. | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-18 | SwiftUI also includes several options for more complex state
management such as the ObservableObject protocol.
Flutter manages local state using a StatefulWidget.
Implement a stateful widget with the following two classes:
a subclass of StatefulWidget
a subclass of State
The State object stores the widget’s state.
To change a widget’s state, call setState() from the State subclass
to tell the framework to redraw the widget.
The following example shows a part of a counter app:
Test in DartPad
View on GitHub
To learn more ways to manage state, check out State management.
Animations
Two main types of UI animations exist.
Implicit that animated from a current value to a new target.
Explicit that animates when asked.
Implicit Animation | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-19 | Explicit that animates when asked.
Implicit Animation
SwiftUI and Flutter take a similar approach to animation.
In both frameworks, you specify parameters like duration, and curve.
In SwiftUI, you use the animate() modifier to handle implicit
animation.
Button
Tap
me
){
angle
+=
45
rotationEffect
degrees
angle
))
animation
easeIn
duration
))
Flutter includes widgets for implicit animation.
This simplifies animating common widgets.
Flutter names these widgets with the following format: AnimatedFoo.
For example: To rotate a button, use the AnimatedRotation class.
This animates the Transform.rotate widget.
Test in DartPad | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-20 | Test in DartPad
View on GitHub
Flutter allows you to create custom implicit animations.
To compose a new animated widget, use the TweenAnimationBuilder.
Explicit Animation
For explicit animations, SwiftUI uses the withAnimation() function.
Flutter includes explicitly animated widgets with names formatted
like FooTransition.
One example would be the RotationTransition class.
Flutter also allows you to create a custom explicit animation using
AnimatedWidget or AnimatedBuilder.
To learn more about animations in Flutter, see Animations overview.
Drawing on the Screen
In SwiftUI, you use CoreGraphics to draw lines and shapes to the
screen.
Flutter has an API based on the Canvas class,
with two classes that help you draw:
CustomPaint that requires a painter: | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-21 | CustomPaint that requires a painter:
Test in DartPad
View on GitHub
CustomPaint(
painter: SignaturePainter(_points),
size: Size.infinite,
),
CustomPainter that implements your algorithm to draw to the canvas.
Test in DartPad
View on GitHub
class SignaturePainter extends CustomPainter {
SignaturePainter(this.points);
final List<Offset?> points; | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-22 | final List<Offset?> points;
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()
..color = Colors.black
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;
for (int i = 0; i < points.length - 1; i++) {
if (points[i] != null && points[i + 1] != null) {
canvas.drawLine(points[i]!, points[i + 1]!, paint);
}
}
}
@override
bool shouldRepaint(SignaturePainter oldDelegate) =>
oldDelegate.points != points;
}
Navigation
This section explains how to navigate between pages of an app,
the push and pop mechanism, and more.
Navigating between pages
Developers build iOS and macOS apps with different pages called
navigation routes. | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-23 | Developers build iOS and macOS apps with different pages called
navigation routes.
In SwiftUI, the NavigationStack represents this stack of pages.
The following example creates an app that displays a list of persons.
To display a person’s details in a new navigation link,
tap on that person.
NavigationStack
path
path
List
ForEach
persons
person
in
NavigationLink
person
name
value
person
navigationDestination
for
Person
self
person
in
PersonView
person
person | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-24 | PersonView
person
person
If you have a small Flutter app without complex linking,
use Navigator with named routes.
After defining your navigation routes,
call your navigation routes using their names.
Name each route in the class passed to the runApp() function.
The following example uses App:
Test in DartPad
View on GitHub
// Defines the route name as a constant
// so that it's reusable.
const detailsPageRouteName = '/details';
class App extends StatelessWidget {
const App({
super.key,
}); | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-25 | @override
Widget build(BuildContext context) {
return CupertinoApp(
home: const HomePage(),
// The [routes] property defines the available named routes
// and the widgets to build when navigating to those routes.
routes: {
detailsPageRouteName: (context) => const DetailsPage(),
},
);
}
}
The following sample generates a list of persons using
mockPersons(). Tapping a person pushes the person’s detail page
to the Navigator using pushNamed().
Test in DartPad
View on GitHub | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-26 | ListView.builder(
itemCount: mockPersons.length,
itemBuilder: (context, index) {
final person = mockPersons.elementAt(index);
final age = '${person.age} years old';
return ListTile(
title: Text(person.name),
subtitle: Text(age),
trailing: const Icon(
Icons.arrow_forward_ios,
),
onTap: () {
// When a [ListTile] that represents a person is
// tapped, push the detailsPageRouteName route
// to the Navigator and pass the person's instance
// to the route.
Navigator.of(context).pushNamed(
detailsPageRouteName,
arguments: person,
);
},
);
},
), | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-27 | Define the DetailsPage widget that displays the details of
each person. In Flutter, you can pass arguments into the
widget when navigating to the new route.
Extract the arguments using ModalRoute.of():
Test in DartPad
View on GitHub
class DetailsPage extends StatelessWidget {
const DetailsPage({super.key});
@override
Widget build(BuildContext context) {
// Read the person instance from the arguments.
final Person person = ModalRoute.of(
context,
)?.settings.arguments as Person;
// Extract the age.
final age = '${person.age} years old';
return Scaffold(
// Display name and age.
body: Column(children: [Text(person.name), Text(age)]),
);
}
}
To create more advanced navigation and routing requirements,
use a routing package such as go_router. | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-28 | To learn more, check out Navigation and routing.
Manually pop back
In SwiftUI, you use the dismiss environment value to pop-back to
the previous screen.
Button
"Pop back"
dismiss
()
In Flutter, use the pop() function of the Navigator class:
Test in DartPad
View on GitHub
Navigating to another app
In SwiftUI, you use the openURL environment variable to open a
URL to another application.
@Environment
(\
openURL
private
var
openUrl
// View code goes here
Button
"Open website"
openUrl
URL
string
"https://google.com" | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-29 | URL
string
"https://google.com"
In Flutter, use the url_launcher plugin.
View on GitHub
Themes, styles, and media
You can style Flutter apps with little effort.
Styling includes switching between light and dark themes,
changing the design of your text and UI components,
and more. This section covers how to style your apps.
Using dark mode
In SwiftUI, you call the preferredColorScheme()
function on a View to use dark mode.
In Flutter, you can control light and dark mode at the app-level.
To control the brightness mode, use the theme property
of the App class:
Test in DartPad
View on GitHub
Styling text | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-30 | View on GitHub
Styling text
In SwiftUI, you use modifier functions to style text.
For example, to change the font of a Text string,
use the font() modifier:
Text
"Hello, world!"
font
system
size
30
weight
heavy
))
foregroundColor
yellow
To style text in Flutter, add a TextStyle widget as the value
of the style parameter of the Text widget.
Test in DartPad
View on GitHub
Styling buttons
In SwiftUI, you use modifier functions to style buttons.
Button
"Do something"
// do something when button is tapped
font
system
size | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-31 | font
system
size
30
weight
bold
))
background
Color
yellow
foregroundColor
Color
blue
To style button widgets in Flutter, set the style of its child,
or modify properties on the button itself.
In the following example:
The color property of CupertinoButton sets its color.
The color property of the child Text widget sets the button
text color.
Test in DartPad
View on GitHub
Using custom fonts
In SwiftUI, you can use a custom font in your app in two steps.
First, add the font file to your SwiftUI project. After adding the file,
use the .font() modifier to apply it to your UI components.
Text | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-32 | Text
"Hello"
font
Font
custom
"BungeeSpice-Regular"
size
40
In Flutter, you control your resources with a file
named pubspec.yaml. This file is platform agnostic.
To add a custom font to your project, follow these steps:
Create a folder called fonts in the project’s root directory.
This optional step helps to organize your fonts.
Add your .ttf, .otf, or .ttc font file into the fonts folder.
Open the pubspec.yaml file within the project.
Find the flutter section.
Add your custom font(s) under the fonts section.
flutter:
fonts:
- family: BungeeSpice
fonts:
- asset: fonts/BungeeSpice-Regular.ttf | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-33 | After you add the font to your project, you can use it as in the
following example:
View on GitHub
Note:
To download custom fonts to use in your apps,
check out Google Fonts.
Bundling images in apps
In SwiftUI, you first add the image files to Assets.xcassets,
then use the Image view to display the images.
To add images in Flutter, follow a method similar to how you added
custom fonts.
Add an images folder to the root directory.
Add this asset to the pubspec.yaml file.
flutter:
assets:
- images/Blueberries.jpg
After adding your image, display it using the Image widget’s
.asset() constructor. This constructor:
Instantiates the given image using the provided path.
Reads the image from the assets bundled with your app. | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
7e4ec76982c4-34 | Reads the image from the assets bundled with your app.
Displays the image on the screen.
To review a complete example, check out the Image docs.
Bundling videos in apps
In SwiftUI, you bundle a local video file with your app in two
steps.
First, you import the AVKit framework, then you instantiate a
VideoPlayer view.
In Flutter, add the video_player plugin to your project.
This plugin allows you to create a video player that works on
Android, iOS, and on the web from the same codebase.
Add the plugin to your app and add the video file to your project.
Add the asset to your pubspec.yaml file.
Use the VideoPlayerController class to load and play your video
file.
To review a complete walkthrough, check out the video_player example. | https://docs.flutter.dev/get-started/flutter-for/swiftui-devs/index.html |
8fc93dc296ae-0 | Flutter for UIKit developers
Overview
Views vs. Widgets
Updating Widgets
Widget layout
Removing Widgets
Animations
Drawing on the screen
Widget opacity
Custom Widgets
Navigation
Navigating between pages
Navigating to another app
Manually pop back
Handling localization
Managing dependencies
ViewControllers
Equivalent of ViewController in Flutter
Listening to lifecycle events
Layouts
Displaying a list view
Detecting what was clicked
Dynamically updating ListView
Creating a scroll view
Gesture detection and touch event handling
Adding a click listener
Handling other gestures
Themes, styles, and media
Using a theme
Using custom fonts
Styling text
Bundling images in apps
Form input
Retrieving user input
Placeholder in a text field
Showing validation errors | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-1 | Retrieving user input
Placeholder in a text field
Showing validation errors
Threading & asynchronicity
Writing asynchronous code
Moving to the background thread
Making network requests
Showing the progress on long running tasks
iOS developers with experience using UIKit
who want to write mobile apps using Flutter
should review this guide.
It explains how to apply existing UIKit knowledge to Flutter.
Note:
If you have experience building apps with SwiftUI,
check out Flutter for SwiftUI developers instead.
Flutter is a framework for building cross-platform applications
that uses the Dart programming language.
To understand some differences between programming with Dart
and programming with Swift, see Learning Dart as a Swift Developer
and Flutter concurrency for Swift developers.
Your iOS and UIKit knowledge and experience
are highly valuable when building with Flutter.
Flutter also makes a number of adaptations
to app behavior when running on iOS.
To learn how, see Platform adaptations. | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-2 | To integrate Flutter code into an existing iOS app,
check out Add Flutter to existing app.
This document can be used as a cookbook by jumping around
and finding questions that are most relevant to your needs.
Overview
Views vs. Widgets
How is react-style, or declarative,
programming different from the
traditional imperative style?
For a comparison, see Introduction to declarative UI.
In UIKit, 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”. | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-3 | 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, a UIKit 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. | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-4 | 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.
Updating Widgets
To update your views in UIKit, 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, with UIKit, 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. | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-5 | 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 StatefulWidgets 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). | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-6 | The following example shows how to use a StatelessWidget.
A commonStatelessWidget is the Text widget.
If you look at the implementation of the Text widget,
you’ll find it subclasses StatelessWidget.
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:
Widget layout
In UIKit, 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: | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-7 | The following example shows how to display a simple widget with padding:
You can add padding to any widget,
which mimics the functionality of constraints in iOS.
You can view the layouts that Flutter has to offer
in the widget catalog.
Removing Widgets
In UIKit, 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:
Animations
In UIKit, you create an animation by calling the
animate(withDuration:animations:) method on a view.
In Flutter, use the animation library
to wrap widgets inside an animated widget. | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-8 | In Flutter, 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
Animations 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: | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-9 | For more information, see Animation & Motion widgets,
the Animations tutorial, and the Animations overview.
Drawing on the screen
In UIKit, you use CoreGraphics to draw lines and shapes to the
screen. Flutter has a different API based on the Canvas class,
with two other classes that help you draw: CustomPaint and CustomPainter,
the latter of which implements your algorithm to draw to the canvas.
To learn how to implement a signature painter in Flutter,
see Collin’s answer on StackOverflow.
Widget opacity
In UIKit, everything has .opacity or .alpha.
In Flutter, most of the time you need to
wrap a widget in an Opacity widget to accomplish this.
Custom Widgets
In UIKit, you typically subclass UIView, or use a pre-existing view,
to override and implement methods that achieve the desired behavior.
In Flutter, build a custom widget by composing smaller widgets
(instead of extending them). | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-10 | For example, how do you build a CustomButton
that takes a label in the constructor?
Create a CustomButton that composes a ElevatedButton with a label,
rather than by extending ElevatedButton:
Then use CustomButton,
just as you’d use any other Flutter widget:
Navigation
This section of the document discusses navigation
between pages of an app, the push and pop mechanism, and more.
Navigating between pages
In UIKit, to travel between view controllers, you can use a
UINavigationController that manages the stack of view controllers
to display.
widget
that manages routes. A route roughly maps to a
To navigate between pages, you have a couple options:
Specify a Map of route names.
Directly navigate to a route.
The following example builds a Map.
Navigate to a route by pushing its name to the Navigator. | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-11 | Navigate to a route by pushing its name to the Navigator.
The Navigator class handles routing in Flutter and is used to get
a result back from a route that you have pushed on the stack.
This is done by awaiting on the Future returned by push().
For example, to start a location route that lets the user select their
location, you might do the following:
And then, inside your location route, once the user has selected their
location, pop() the stack with the result:
Navigating to another app
In UIKit, to send the user to another application,
you use a specific URL scheme.
For the system level apps, the scheme depends on the app.
To implement this functionality in Flutter,
create a native platform integration, or use an
existing plugin, such as url_launcher.
Manually pop back
Calling SystemNavigator.pop() from your Dart code
invokes the following iOS code:
UIViewController | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
8fc93dc296ae-12 | UIViewController
viewController
UIApplication
sharedApplication
].
keyWindow
rootViewController
if
([
viewController
isKindOfClass
:[
UINavigationController
class
]])
[((
UINavigationController
viewController
popViewControllerAnimated
NO
];
If that doesn’t do what you want, you can create your own
platform channel to invoke arbitrary iOS code.
Handling localization
Unlike iOS, which has the Localizable.strings file,
Flutter doesn’t currently have a dedicated system for handling strings.
At the moment, the best practice is to declare your copy text
in a class as static fields and access them from there. For example: | https://docs.flutter.dev/get-started/flutter-for/uikit-devs/index.html |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.