id
stringlengths
14
17
text
stringlengths
23
1.11k
source
stringlengths
35
114
a70a020710a3-10
(Set<MaterialState> states) { return states.contains(MaterialState.disabled) ? null : Colors.blue; }), ), onPressed: null, child: const Text('Sign up'), ), ], ), ); } } {$ end main.dart $} {$ begin test.dart $} // Avoid warning on "double _formProgress = 0;" //ignore_for_file: prefer_final_fields {$ end test.dart $}
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-11
Important: This page uses an embedded version of DartPad to display examples and exercises. If you see empty boxes instead of DartPads, go to the DartPad troubleshooting page. Run the example. Click the Run button to run the example. Note that you can type into the text fields, but the Sign up button is disabled. Copy the code. Click the clipboard icon in the upper right of the code pane to copy the Dart code to your clipboard. Create a new Flutter project. From your IDE, editor, or at the command line, create a new Flutter project and name it signin_example. Replace the contents of lib/main.dart with the contents of the clipboard. Observations The entire code for this example lives in the lib/main.dart file. If you know Java, the Dart language should feel very familiar.
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-12
If you know Java, the Dart language should feel very familiar. All of the app’s UI is created in Dart code. For more information, see Introduction to declarative UI. The app’s UI adheres to Material Design, a visual design language that runs on any device or platform. You can customize the Material Design widgets, but if you prefer something else, Flutter also offers the Cupertino widget library, which implements the current iOS design language. Or you can create your own custom widget library. In Flutter, almost everything is a Widget. Even the app itself is a widget. The app’s UI can be described as a widget tree. Step 1: Show the Welcome screen
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-13
Step 1: Show the Welcome screen The SignUpForm class is a stateful widget. This simply means that the widget stores information that can change, such as user input, or data from a feed. Since widgets themselves are immutable (can’t be modified once created), Flutter stores state information in a companion class, called the State class. In this lab, all of your edits will be made to the private _SignUpFormState class. Fun fact The Dart compiler enforces privacy for any identifier prefixed with an underscore. For more information, see the Effective Dart Style Guide. First, in your lib/main.dart file, add the following class definition for the WelcomeScreen widget after the SignUpScreen class: Next, you will enable the button to display the screen and create a method to display it.
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-14
Locate the build() method for the _SignUpFormState class. This is the part of the code that builds the SignUp button. Notice how the button is defined: It’s a TextButton with a blue background, white text that says Sign up and, when pressed, does nothing. Update the onPressed property. Change the onPressed property to call the (non-existent) method that will display the welcome screen. Change onPressed: null to the following: onPressed: _showWelcomeScreen, Add the _showWelcomeScreen method. Fix the error reported by the analyzer that _showWelcomeScreen is not defined. Directly above the build() method, add the following function: void _showWelcomeScreen() { Navigator.of(context).pushNamed('/welcome'); }
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-15
Add the /welcome route. Create the connection to show the new screen. In the build() method for SignUpApp, add the following route below '/': '/welcome': (context) => const WelcomeScreen(), Run the app. The Sign up button should now be enabled. Click it to bring up the welcome screen. Note how it animates in from the bottom. You get that behavior for free. Observations The _showWelcomeScreen() function is used in the build() method as a callback function. Callback functions are often used in Dart code and, in this case, this means “call this method when the button is pressed”. The const keyword in front of the constructor is very important. When Flutter encounters a constant widget, it short-circuits most of the rebuilding work under the hood making the rendering more efficient.
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-16
Flutter has only one Navigator object. This widget manages Flutter’s screens (also called routes or pages) inside a stack. The screen at the top of the stack is the view that is currently displayed. Pushing a new screen to this stack switches the display to that new screen. This is why the _showWelcomeScreen function pushes the WelcomeScreen onto the Navigator’s stack. The user clicks the button and, voila, the welcome screen appears. Likewise, calling pop() on the Navigator returns to the previous screen. Because Flutter’s navigation is integrated into the browser’s navigation, this happens implicitly when clicking the browser’s back arrow button. Step 2: Enable sign in progress tracking This sign in screen has three fields. Next, you will enable the ability to track the user’s progress on filling in the form fields, and update the app’s UI when the form is complete.
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-17
Note: This example does not validate the accuracy of the user input. That is something you can add later using form validation, if you like. Add a method to update _formProgress. In the _SignUpFormState class, add a new method called _updateFormProgress(): void _updateFormProgress() { var progress = 0.0; final controllers = [ _firstNameTextController, _lastNameTextController, _usernameTextController ]; for (final controller in controllers) { if (controller.value.text.isNotEmpty) { progress += 1 / controllers.length; } } setState(() { _formProgress = progress; }); } This method updates the _formProgress field based on the the number of non-empty text fields.
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-18
Call _updateFormProgress when the form changes. In the build() method of the _SignUpFormState class, add a callback to the Form widget’s onChanged argument. Add the code below marked as NEW: return Form( onChanged: _updateFormProgress, // NEW child: Column( Update the onPressed property (again). In step 1, you modified the onPressed property for the Sign up button to display the welcome screen. Now, update that button to display the welcome screen only when the form is completely filled in:
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-19
TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith( (Set<MaterialState> states) { return states.contains(MaterialState.disabled) ? null : Colors.white; }), backgroundColor: MaterialStateProperty.resolveWith( (Set<MaterialState> states) { return states.contains(MaterialState.disabled) ? null : Colors.blue; }), ), onPressed: _formProgress == 1 ? _showWelcomeScreen : null, // UPDATED child: const Text('Sign up'), ), Run the app. The Sign up button is initially disabled, but becomes enabled when all three text fields contain (any) text. Observations
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-20
Observations Calling a widget’s setState() method tells Flutter that the widget needs to be updated on screen. The framework then disposes of the previous immutable widget (and its children), creates a new one (with its accompanying child widget tree), and renders it to screen. For this to work seamlessly, Flutter needs to be fast. The new widget tree must be created and rendered to screen in less than 1/60th of a second to create a smooth visual transition—especially for an animation. Luckily Flutter is fast.
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-21
The progress field is defined as a floating value, and is updated in the _updateFormProgress method. When all three fields are filled in, _formProgress is set to 1.0. When _formProgress is set to 1.0, the onPressed callback is set to the _showWelcomeScreen method. Now that its onPressed argument is non-null, the button is enabled. Like most Material Design buttons in Flutter, TextButtons are disabled by default if their onPressed and onLongPress callbacks are null. Notice that the _updateFormProgress passes a function to setState(). This is called an anonymous function and has the following syntax: methodName(() {...}); Where methodName is a named function that takes an anonymous callback function as an argument. The Dart syntax in the last step that displays the welcome screen is: _formProgress == 1 ? _showWelcomeScreen : null
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-22
_formProgress == 1 ? _showWelcomeScreen : null This is a Dart conditional assignment and has the syntax: condition ? expression1 : expression2. If the expression _formProgress == 1 is true, the entire expression results in the value on the left hand side of the :, which is the _showWelcomeScreen method in this case. Step 2.5: Launch Dart DevTools How do you debug a Flutter web app? It’s not too different from debugging any Flutter app. You want to use Dart DevTools! (Not to be confused with Chrome DevTools.) Our app currently has no bugs, but let’s check it out anyway. The following instructions for launching DevTools applies to any workflow, but there is a short cut if you’re using IntelliJ. See the tip at the end of this section for more information.
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-23
Run the app. If your app isn’t currently running, launch it. Select the Chrome device from the pull down and launch it from your IDE or, from the command line, use flutter run -d chrome, Get the web socket info for DevTools. At the command line, or in the IDE, you should see a message stating something like the following: Launching lib/main.dart on Chrome in debug mode... Building application for the web... 11.7s Attempting to connect to browser instance.. Debug service listening on ws://127.0.0.1:54998/pJqWWxNv92s= Copy the address of the debug service, shown in bold. You will need that to launch DevTools.
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-24
Ensure that DevTools is installed. Do you have DevTools installed? If you are using an IDE, make sure you have the Flutter and Dart plugins set up, as described in the VS Code and Android Studio and IntelliJ pages. If you are working at the command line, launch the DevTools server as explained in the DevTools command line page. Connect to DevTools. When DevTools launches, you should see something like the following: Serving DevTools at http://127.0.0.1:9100 Go to this URL in a Chrome browser. You should see the DevTools launch screen. It should look like the following: Connect to running app. Under Connect to a running site, paste the ws location that you copied in step 2, and click Connect. You should now see Dart DevTools running successfully in your Chrome browser: Congratulations, you are now running Dart DevTools!
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-25
Congratulations, you are now running Dart DevTools! Note: This is not the only way to launch DevTools. If you are using IntelliJ, you can open DevTools by going to Flutter Inspector -> More Actions -> Open DevTools: Set a breakpoint. Now that you have DevTools running, select the Debugger tab in the blue bar along the top. The debugger pane appears and, in the lower left, see a list of libraries used in the example. Select lib/main.dart to display your Dart code in the center pane. Set a breakpoint. In the Dart code, scroll down to where progress is updated: for (final controller in controllers) { if (controller.value.text.isNotEmpty) { progress += 1 / controllers.length; } }
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-26
Place a breakpoint on the line with the for loop by clicking to the left of the line number. The breakpoint now appears in the Breakpoints section to the left of the window. Trigger the breakpoint. In the running app, click one of the text fields to gain focus. The app hits the breakpoint and pauses. In the DevTools screen, you can see on the left the value of progress, which is 0. This is to be expected, since none of the fields are filled in. Step through the for loop to see the program execution. Resume the app. Resume the app by clicking the green Resume button in the DevTools window. Delete the breakpoint. Delete the breakpoint by clicking it again, and resume the app. This gives you a tiny glimpse of what is possible using DevTools, but there is lots more! For more information, see the DevTools documentation. Step 3: Add animation for sign in progress
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-27
Step 3: Add animation for sign in progress It’s time to add animation! In this final step, you’ll create the animation for the LinearProgressIndicator at the top of the sign in area. The animation has the following behavior: When the app starts, a tiny red bar appears across the top of the sign in area. When one text field contains text, the red bar turns orange and animates 0.15 of the way across the sign in area. When two text fields contain text, the orange bar turns yellow and animates half of the way across the sign in area. When all three text fields contain text, the orange bar turns green and animates all the way across the sign in area. Also, the Sign up button becomes enabled. Add an AnimatedProgressIndicator. At the bottom of the file, add this widget: class AnimatedProgressIndicator extends StatefulWidget { final double value;
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-28
class AnimatedProgressIndicator extends StatefulWidget { final double value; const AnimatedProgressIndicator({ required this.value, }); @override State<AnimatedProgressIndicator> createState() { return _AnimatedProgressIndicatorState(); } } class _AnimatedProgressIndicatorState extends State<AnimatedProgressIndicator> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<Color?> _colorAnimation; late Animation<double> _curveAnimation; @override void initState() { super.initState(); _controller = AnimationController( duration: Duration(milliseconds: 1200), vsync: this);
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-29
final colorTween = TweenSequence([ TweenSequenceItem( tween: ColorTween(begin: Colors.red, end: Colors.orange), weight: 1, ), TweenSequenceItem( tween: ColorTween(begin: Colors.orange, end: Colors.yellow), weight: 1, ), TweenSequenceItem( tween: ColorTween(begin: Colors.yellow, end: Colors.green), weight: 1, ), ]); _colorAnimation = _controller.drive(colorTween); _curveAnimation = _controller.drive(CurveTween(curve: Curves.easeIn)); } @override void didUpdateWidget(oldWidget) { super.didUpdateWidget(oldWidget); _controller.animateTo(widget.value); }
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-30
@override Widget build(BuildContext context) { return AnimatedBuilder( animation: _controller, builder: (context, child) => LinearProgressIndicator( value: _curveAnimation.value, valueColor: _colorAnimation, backgroundColor: _colorAnimation.value?.withOpacity(0.4), ), ); } } The didUpdateWidget function updates the AnimatedProgressIndicatorState whenever AnimatedProgressIndicator changes. Use the new AnimatedProgressIndicator. Then, replace the LinearProgressIndicator in the Form with this new AnimatedProgressIndicator: child: Column( mainAxisSize: MainAxisSize.min, children: [ AnimatedProgressIndicator(value: _formProgress), // NEW Text('Sign up', style: Theme.of(context).textTheme.headlineMedium), Padding(
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-31
This widget uses an AnimatedBuilder to animate the progress indicator to the latest value. Run the app. Type anything into the three fields to verify that the animation works, and that clicking the Sign up button brings up the Welcome screen. Complete sample Observations You can use an AnimationController to run any animation. AnimatedBuilder rebuilds the widget tree when the value of an Animation changes. Using a Tween, you can interpolate between almost any value, in this case, Color. What next? Congratulations! You have created your first web app using Flutter! If you’d like to continue playing with this example, perhaps you could add form validation. For advice on how to do this, see the Building a form with validation recipe in the Flutter cookbook.
https://docs.flutter.dev/get-started/codelab-web/index.html
a70a020710a3-32
For more information on Flutter web apps, Dart DevTools, or Flutter animations, see the following: Animation docs Dart DevTools Implicit animations codelab Web samples
https://docs.flutter.dev/get-started/codelab-web/index.html
6394db101601-0
Install Test drive Set up an editor Get started Set up an editor You can build apps with Flutter using any text editor combined with Flutter’s command-line tools. However, we recommend using one of our editor plugins for an even better experience. These plugins provide you with code completion, syntax highlighting, widget editing assists, run & debug support, and more. Use the following steps to add an editor plugin for VS Code, Android Studio, IntelliJ, or Emacs. If you want to use a different editor, that’s OK, skip ahead to the next step: Test drive. Visual Studio Code Android Studio and IntelliJ Emacs Install VS Code VS Code is a lightweight editor with complete Flutter app execution and debug support. VS Code, latest stable version Install the Flutter and Dart plugins
https://docs.flutter.dev/get-started/editor/index.html
6394db101601-1
VS Code, latest stable version Install the Flutter and Dart plugins Start VS Code. Invoke View > Command Palette…. Type “install”, and select Extensions: Install Extensions. Type “flutter” in the extensions search field, select Flutter in the list, and click Install. This also installs the required Dart plugin. Validate your setup with the Flutter Doctor Invoke View > Command Palette…. Type “doctor”, and select the Flutter: Run Flutter Doctor. Review the output in the OUTPUT pane for any issues. Make sure to select Flutter from the dropdown in the different Output Options. Install Android Studio Android Studio offers a complete, integrated IDE experience for Flutter. Android Studio, version 2020.3.1 (Arctic Fox) or later
https://docs.flutter.dev/get-started/editor/index.html
6394db101601-2
Alternatively, you can also use IntelliJ: IntelliJ IDEA Community, version 2021.2 or later IntelliJ IDEA Ultimate, version 2021.2 or later Install the Flutter and Dart plugins The installation instructions vary by platform. Mac Use the following instructions for macos: Start Android Studio. Open plugin preferences (Preferences > Plugins as of v3.6.3.0 or later). Select the Flutter plugin and click Install. Click Yes when prompted to install the Dart plugin. Click Restart when prompted. Linux or Windows Use the following instructions for Linux or Windows: Open plugin preferences (File > Settings > Plugins). Select Marketplace, select the Flutter plugin and click Install. Install Emacs
https://docs.flutter.dev/get-started/editor/index.html
6394db101601-3
Install Emacs Emacs is a lightweight editor with support for Flutter and Dart. Emacs, latest stable version Install the lsp-dart package For information on how to install and use the package, see the lsp-dart documentation. Install Test drive
https://docs.flutter.dev/get-started/editor/index.html
04032aa23bfa-0
Flutter for Android developers Views What is the equivalent of a View in Flutter? How do I update widgets? How do I lay out my widgets? Where is my XML layout file? How do I add or remove a component from my layout? How do I animate a widget? How do I use a Canvas to draw/paint? How do I build custom widgets? Intents What is the equivalent of an Intent in Flutter? How do I handle incoming intents from external applications in Flutter? What is the equivalent of startActivityForResult()? Async UI What is the equivalent of runOnUiThread() in Flutter? How do you move work to a background thread? What is the equivalent of OkHttp on Flutter? How do I show the progress for a long-running task? Project structure & resources
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-1
Project structure & resources Where do I store my resolution-dependent image files? Where do I store strings? How do I handle localization? What is the equivalent of a Gradle file? How do I add dependencies? Activities and fragments What are the equivalent of activities and fragments in Flutter? How do I listen to Android activity lifecycle events? Layouts What is the equivalent of a LinearLayout? What is the equivalent of a RelativeLayout? What is the equivalent of a ScrollView? How do I handle landscape transitions in Flutter? Gesture detection and touch event handling How do I add an onClick listener to a widget in Flutter? How do I handle other gestures on widgets? Listviews & adapters What is the alternative to a ListView in Flutter? How do I know which list item is clicked on? How do I update ListView’s dynamically? Working with text
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-2
Working with text How do I set custom fonts on my Text widgets? How do I style my Text widgets? Form input What is the equivalent of a “hint” on an Input? How do I show validation errors? Flutter plugins How do I access the GPS sensor? How do I access the camera? How do I log in with Facebook? How do I use Firebase features? How do I build my own custom native integrations? How do I use the NDK in my Flutter application? Themes How do I theme my app? Databases and local storage How do I access Shared Preferences? How do I access SQLite in Flutter? Debugging What tools can I use to debug my app in Flutter? Notifications How do I set up push notifications?
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-3
Notifications How do I set up push notifications? 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. Note: To integrate Flutter code into your Android app, see Add Flutter to existing app. 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
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-4
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.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-5
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, Widgets are immutable and are not updated directly, instead you have to work with the widget’s state.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-6
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.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-7
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. 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: How do I lay out my widgets? Where is my XML layout file?
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-8
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: You can view some of the layouts that Flutter has to offer in the widget catalog. 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: How do I animate a widget?
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-9
How do I animate a widget? In Android, you either create animations using XML, or call the animate() method on a view. In Flutter, animate widgets using the animation library by wrapping widgets inside an animated widget. 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.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-10
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: For more information, see Animation & Motion widgets, the Animations tutorial, and the Animations overview. How do I use a Canvas to draw/paint? In Android, you would use the Canvas and Drawable to draw images and shapes to the screen. Flutter has a similar Canvas API as well, since it is based on the same low-level rendering engine, Skia. As a result, painting to a canvas in Flutter is a very familiar task for Android developers. Flutter has two classes that help you draw to the canvas: CustomPaint and CustomPainter, the latter of which implements your algorithm to draw to the canvas.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-11
To learn how to implement a signature painter in Flutter, see Collin’s answer on Custom Paint. How do I build custom widgets? In Android, you typically subclass View, 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). It is somewhat similar to implementing a custom ViewGroup in Android, where all the building blocks are already existing, but you provide a different behavior—for example, custom layout logic. 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: Intents What is the equivalent of an Intent in Flutter?
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-12
Intents What is the equivalent of an Intent in Flutter? In Android, there are two main use cases for Intents: navigating between Activities, and communicating with components. Flutter, on the other hand, does not have the concept of intents, although you can still start intents through native integrations (using a plugin). Flutter doesn’t really have a direct equivalent to activities and fragments; rather, in Flutter you navigate between screens, using a Navigator and Routes, all within the same Activity. A Route is an abstraction for a “screen” or “page” of an app, and a Navigator is a widget that manages routes. A route roughly maps to an Activity, but it does not carry the same meaning. A navigator can push and pop routes to move from screen to screen. Navigators work like a stack on which you can push() new routes you want to navigate to, and from which you can pop() routes when you want to “go back”.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-13
In Android, you declare your activities inside the app’s AndroidManifest.xml. In Flutter, you have a couple options to navigate between pages: Specify a Map of route names. (using MaterialApp) Directly navigate to a route. (using WidgetsApp) The following example builds a Map. Navigate to a route by pushing its name to the Navigator. The other popular use-case for Intents is to call external components such as a Camera or File picker. For this, you would need to create a native platform integration (or use an existing plugin). To learn how to build a native platform integration, see developing packages and plugins. How do I handle incoming intents from external applications in Flutter? Flutter can handle incoming intents from Android by directly talking to the Android layer and requesting the data that was shared.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-14
The following example registers a text share intent filter on the native activity that runs our Flutter code, so other apps can share text with our Flutter app. The basic flow implies that we first handle the shared text data on the Android native side (in our Activity), and then wait until Flutter requests for the data to provide it using a MethodChannel. First, register the intent filter for all intents in AndroidManifest.xml: <activity android:name= ".MainActivity" android:launchMode= "singleTop" android:theme= "@style/LaunchTheme" android:configChanges= "orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection" android:hardwareAccelerated= "true" android:windowSoftInputMode= "adjustResize"
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-15
android:windowSoftInputMode= "adjustResize" <!-- ... --> <intent-filter> <action android:name= "android.intent.action.SEND" /> <category android:name= "android.intent.category.DEFAULT" /> <data android:mimeType= "text/plain" /> </intent-filter> </activity> Then in MainActivity, handle the intent, extract the text that was shared from the intent, and hold onto it. When Flutter is ready to process, it requests the data using a platform channel, and it’s sent across from the native side: package com.example.shared import
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-16
package com.example.shared import android.content.Intent import android.os.Bundle import androidx.annotation.NonNull import io.flutter.plugin.common.MethodChannel import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugins.GeneratedPluginRegistrant public class MainActivity extends FlutterActivity private String sharedText private static final String CHANNEL "app.channel.shared.data"
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-17
CHANNEL "app.channel.shared.data" @Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState ); Intent intent getIntent (); String action intent getAction (); String type intent getType (); if Intent ACTION_SEND equals action && type != null if "text/plain" equals
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-18
if "text/plain" equals type )) handleSendText intent ); // Handle text being sent @Override public void configureFlutterEngine @NonNull FlutterEngine flutterEngine GeneratedPluginRegistrant registerWith flutterEngine ); new MethodChannel flutterEngine getDartExecutor (). getBinaryMessenger (), CHANNEL setMethodCallHandler call result > if call method
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-19
> if call method contentEquals "getSharedText" )) result success sharedText ); sharedText null ); void handleSendText Intent intent sharedText intent getStringExtra Intent EXTRA_TEXT ); Finally, request the data from the Flutter side when the widget is rendered: What is the equivalent of startActivityForResult()? 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().
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-20
For example, to start a location route that lets the user select their location, you could do the following: And then, inside your location route, once the user has selected their location you can pop the stack with the result: Async UI What is the equivalent of runOnUiThread() in Flutter? Dart has a single-threaded execution model, with support for Isolates (a way to run Dart code on another thread), an event loop, and asynchronous programming. Unless you spawn an Isolate, your Dart code runs in the main UI thread and is driven by an event loop. Flutter’s event loop is equivalent to Android’s main Looper—that is, the Looper that is attached to the main thread.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-21
Dart’s single-threaded model doesn’t mean you need to run everything as a blocking operation that causes the UI to freeze. Unlike Android, which requires you to keep the main thread free at all times, in Flutter, use the asynchronous facilities that the Dart language provides, such as async/await, to perform asynchronous work. You might be familiar with the async/await paradigm if you’ve used it in C#, Javascript, or if you have used Kotlin’s coroutines. For example, you can run network code without causing the UI to hang by using async/await and letting Dart do the heavy lifting: Once the awaited network call is done, update the UI by calling setState(), which triggers a rebuild of the widget sub-tree and updates the data. The following example loads data asynchronously and displays it in a ListView: Refer to the next section for more information on doing work in the background, and how Flutter differs from Android.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-22
How do you move work to a background thread? In Android, when you want to access a network resource you would typically move to a background thread and do the work, as to not block the main thread, and avoid ANRs. For example, you might be using an AsyncTask, a LiveData, an IntentService, a JobScheduler job, or an RxJava pipeline with a scheduler that works on background threads. Since Flutter is single threaded and runs an event loop (like Node.js), you don’t have to worry about thread management or spawning background threads. If you’re doing I/O-bound work, such as disk access or a network call, then you can safely use async/await and you’re all set. If, on the other hand, you need to do computationally intensive work that keeps the CPU busy, you want to move it to an Isolate to avoid blocking the event loop, like you would keep any sort of work out of the main thread in Android.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-23
For I/O-bound work, declare the function as an async function, and await on long-running tasks inside the function: This is how you would typically do network or database calls, which are both I/O operations. On Android, when you extend AsyncTask, you typically override 3 methods, onPreExecute(), doInBackground() and onPostExecute(). There is no equivalent in Flutter, since you await on a long running function, and Dart’s event loop takes care of the rest. However, there are times when you might be processing a large amount of data and your UI hangs. In Flutter, use Isolates to take advantage of multiple CPU cores to do long-running or computationally intensive tasks.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-24
Isolates are separate execution threads that do not share any memory with the main execution memory heap. This means you can’t access variables from the main thread, or update your UI by calling setState(). Unlike Android threads, Isolates are true to their name, and cannot share memory (in the form of static fields, for example). The following example shows, in a simple isolate, how to share data back to the main thread to update the UI. Here, dataLoader() is the Isolate that runs in its own separate execution thread. In the isolate you can perform more CPU intensive processing (parsing a big JSON, for example), or perform computationally intensive math, such as encryption or signal processing. You can run the full example below: What is the equivalent of OkHttp on Flutter? Making a network call in Flutter is easy when you use the popular http package.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-25
While the http package doesn’t have every feature found in OkHttp, it abstracts away much of the networking that you would normally implement yourself, making it a simple way to make network calls. To use the http package, add it to your dependencies in pubspec.yaml: dependencies ... http ^0.11.3+16 To make a network call, call await on the async function http.get(): How do I show the progress for a long-running task? In Android you would typically show a ProgressBar view in your UI while executing a long running task on a background thread. In Flutter, use a ProgressIndicator widget. Show the progress programmatically by controlling when it’s rendered through a boolean flag. Tell Flutter to update its state before your long-running task starts, and hide it after it ends.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-26
In the following example, the build function is separated into three different functions. If showLoadingDialog is true (when widgets.isEmpty), then render the ProgressIndicator. Otherwise, render the ListView with the data returned from a network call. Project structure & resources Where do I store my resolution-dependent image files? While Android treats resources and assets as distinct items, Flutter apps have only assets. All resources that would live in the res/drawable-* folders on Android, are placed in an assets folder for Flutter. Flutter follows a simple density-based format like iOS. Assets might be 1.0x, 2.0x, 3.0x, or any other multiplier. Flutter doesn’t have dps but there are logical pixels, which are basically the same as device-independent pixels. The so-called devicePixelRatio expresses the ratio of physical pixels in a single logical pixel. The equivalent to Android’s density buckets are: ldpi
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-27
The equivalent to Android’s density buckets are: ldpi 0.75x mdpi 1.0x hdpi 1.5x xhdpi 2.0x xxhdpi 3.0x xxxhdpi 4.0x Assets are located in any arbitrary folder—Flutter has no predefined folder structure. You declare the assets (with location) in the pubspec.yaml file, and Flutter picks them up. Note that before Flutter 1.0 beta 2, assets defined in Flutter were not accessible from the native side, and vice versa, native assets and resources weren’t available to Flutter, as they lived in separate folders.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-28
As of Flutter beta 2, assets are stored in the native asset folder, and are accessed on the native side using Android’s AssetManager: val flutterAssetStream assetManager open "flutter_assets/assets/my_flutter_asset.png" As of Flutter beta 2, Flutter still cannot access native resources, nor it can access native assets. To add a new image asset called my_icon.png to our Flutter project, for example, and deciding that it should live in a folder we arbitrarily called images, you would put the base image (1.0x) in the images folder, and all the other variants in sub-folders called with the appropriate ratio multiplier: Next, you’ll need to declare these images in your pubspec.yaml file: assets images/my_icon.jpeg You can then access your images using AssetImage:
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-29
You can then access your images using AssetImage: or directly in an Image widget: Where do I store strings? How do I handle localization? Flutter currently doesn’t have a dedicated resources-like system for strings. At the moment, the best practice is to hold your copy text in a class as static fields and accessing them from there. For example: Then in your code, you can access your strings as such: Flutter has basic support for accessibility on Android, though this feature is a work in progress. Flutter developers are encouraged to use the intl package for internationalization and localization. What is the equivalent of a Gradle file? How do I add dependencies? In Android, you add dependencies by adding to your Gradle build script. Flutter uses Dart’s own build system, and the Pub package manager. The tools delegate the building of the native Android and iOS wrapper apps to the respective build systems.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-30
While there are Gradle files under the android folder in your Flutter project, only use these if you are adding native dependencies needed for per-platform integration. In general, use pubspec.yaml to declare external dependencies to use in Flutter. A good place to find Flutter packages is pub.dev. Activities and fragments What are the equivalent of activities and fragments in Flutter? In Android, an Activity represents a single focused thing the user can do. A Fragment represents a behavior or a portion of user interface. Fragments are a way to modularize your code, compose sophisticated user interfaces for larger screens, and help scale your application UI. In Flutter, both of these concepts fall under the umbrella of Widgets. To learn more about the UI for building Activities and Fragements, see the community-contributed Medium article, Flutter for Android Developers: How to design Activity UI in Flutter.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-31
As mentioned in the Intents section, screens in Flutter are represented by Widgets since everything is a widget in Flutter. Use a Navigator to move between different Routes that represent different screens or pages, or perhaps different states or renderings of the same data. How do I listen to Android activity lifecycle events? In Android, you can override methods from the Activity to capture lifecycle methods for the activity itself, or register ActivityLifecycleCallbacks on the Application. In Flutter, you have neither concept, but you can instead listen to lifecycle events by hooking into the WidgetsBinding observer and listening to the didChangeAppLifecycleState() change event. The observable lifecycle events are: detached — The application is still hosted on a flutter engine but is detached from any host views. inactive — The application is in an inactive state and is not receiving user input.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-32
inactive — The application is in an inactive state and is not receiving user input. paused — The application is not currently visible to the user, not responding to user input, and running in the background. This is equivalent to onPause() in Android. resumed — The application is visible and responding to user input. This is equivalent to onPostResume() in Android. For more details on the meaning of these states, see the AppLifecycleStatus documentation.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-33
For more details on the meaning of these states, see the AppLifecycleStatus documentation. As you might have noticed, only a small minority of the Activity lifecycle events are available; while FlutterActivity does capture almost all the activity lifecycle events internally and send them over to the Flutter engine, they’re mostly shielded away from you. Flutter takes care of starting and stopping the engine for you, and there is little reason for needing to observe the activity lifecycle on the Flutter side in most cases. If you need to observe the lifecycle to acquire or release any native resources, you should likely be doing it from the native side, at any rate. Here’s an example of how to observe the lifecycle status of the containing activity: Layouts What is the equivalent of a LinearLayout?
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-34
Layouts What is the equivalent of a LinearLayout? In Android, a LinearLayout is used to lay your widgets out linearly—either horizontally or vertically. In Flutter, use the Row or Column widgets to achieve the same result. If you notice the two code samples are identical with the exception of the “Row” and “Column” widget. The children are the same and this feature can be exploited to develop rich layouts that can change overtime with the same children. To learn more about building linear layouts, see the community-contributed Medium article Flutter for Android Developers: How to design LinearLayout in Flutter. What is the equivalent of a RelativeLayout? A RelativeLayout lays your widgets out relative to each other. In Flutter, there are a few ways to achieve the same result.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-35
You can achieve the result of a RelativeLayout by using a combination of Column, Row, and Stack widgets. You can specify rules for the widgets constructors on how the children are laid out relative to the parent. For a good example of building a RelativeLayout in Flutter, see Collin’s answer on StackOverflow. What is the equivalent of a ScrollView? In Android, use a ScrollView to lay out your widgets—if the user’s device has a smaller screen than your content, it scrolls. In Flutter, the easiest way to do this is using the ListView widget. This might seem like overkill coming from Android, but in Flutter a ListView widget is both a ScrollView and an Android ListView. How do I handle landscape transitions in Flutter? FlutterView handles the config change if AndroidManifest.xml contains: android:configChanges="orientation|screenSize" Gesture detection and touch event handling
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-36
Gesture detection and touch event handling How do I add an onClick listener to a widget in Flutter? In Android, you can attach onClick to views such as button by calling the method ‘setOnClickListener’. In Flutter there are two ways of adding touch listeners: If the Widget supports event detection, pass a function to it and handle it in the function. For example, the ElevatedButton has an onPressed parameter: If the Widget doesn’t support event detection, wrap the widget in a GestureDetector and pass a function to the onTap parameter. How do I handle other gestures on widgets? Using the GestureDetector, you can listen to a wide range of Gestures such as: Tap
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-37
Tap onTapDown - A pointer that might cause a tap has contacted the screen at a particular location. onTapUp - A pointer that triggers a tap has stopped contacting the screen at a particular location. onTap - A tap has occurred. onTapCancel - The pointer that previously triggered the onTapDown won’t cause a tap. Double tap onDoubleTap - The user tapped the screen at the same location twice in quick succession. Long press onLongPress - A pointer has remained in contact with the screen at the same location for a long period of time. Vertical drag
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-38
Vertical drag onVerticalDragStart - A pointer has contacted the screen and might begin to move vertically. onVerticalDragUpdate - A pointer in contact with the screen has moved further in the vertical direction. onVerticalDragEnd - A pointer that was previously in contact with the screen and moving vertically is no longer in contact with the screen and was moving at a specific velocity when it stopped contacting the screen. Horizontal drag onHorizontalDragStart - A pointer has contacted the screen and might begin to move horizontally. onHorizontalDragUpdate - A pointer in contact with the screen has moved further in the horizontal direction. onHorizontalDragEnd - A pointer that was previously in contact with the screen and moving horizontally is no longer in contact with the screen and was moving at a specific velocity when it stopped contacting the screen. The following example shows a GestureDetector that rotates the Flutter logo on a double tap:
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-39
Listviews & adapters What is the alternative to a ListView in Flutter? The equivalent to a ListView in Flutter is … a ListView! In an Android ListView, you create an adapter and pass it into the ListView, which renders each row with what your adapter returns. However, you have to make sure you recycle your rows, otherwise, you get all sorts of crazy visual glitches and memory issues. Due to Flutter’s immutable widget pattern, you pass a list of widgets to your ListView, and Flutter takes care of making sure that scrolling is fast and smooth. How do I know which list item is clicked on? In Android, the ListView has a method to find out which item was clicked, ‘onItemClickListener’. In Flutter, use the touch handling provided by the passed-in widgets. How do I update ListView’s dynamically? On Android, you update the adapter and call notifyDataSetChanged.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-40
On Android, you update the adapter and call notifyDataSetChanged. In Flutter, if you were to update the list of widgets inside a setState(), you would quickly see that your data did not change visually. This is because when setState() is called, the Flutter rendering engine looks at the widget tree to see if anything has changed. When it gets to your ListView, it performs a == check, and determines that the two ListViews are the same. Nothing has changed, so no update is required. For a simple way to update your ListView, create a new List inside of setState(), and copy the data from the old list to the new list. While this approach is simple, it is not recommended for large data sets, as shown in the next example. The recommended, efficient, and effective way to build a list uses a ListView.Builder. This method is great when you have a dynamic List or a List with very large amounts of data. This is essentially the equivalent of RecyclerView on Android, which automatically recycles list elements for you:
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-41
Instead of creating a “ListView”, create a ListView.builder that takes two key parameters: the initial length of the list, and an ItemBuilder function. The ItemBuilder function is similar to the getView function in an Android adapter; it takes a position, and returns the row you want rendered at that position. Finally, but most importantly, notice that the onTap() function doesn’t recreate the list anymore, but instead .adds to it. Working with text How do I set custom fonts on my Text widgets? In Android SDK (as of Android O), you create a Font resource file and pass it into the FontFamily param for your TextView. In Flutter, place the font file in a folder and reference it in the pubspec.yaml file, similar to how you import images. fonts family MyCustomFont fonts asset fonts/MyCustomFont.ttf
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-42
asset fonts/MyCustomFont.ttf style italic Then assign the font to your Text widget: How do I style my Text widgets? Along with fonts, you can customize other styling elements on a Text widget. The style parameter of a Text widget takes a TextStyle object, where you can customize many parameters, such as: color decoration decorationColor decorationStyle fontFamily fontSize fontStyle fontWeight hashCode height inherit letterSpacing textBaseline wordSpacing Form input For more information on using Forms, see Retrieve the value of a text field, from the Flutter cookbook.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-43
What is the equivalent of a “hint” on an Input? In Flutter, you can easily show a “hint” or a placeholder text for your input by adding an InputDecoration object to the decoration constructor parameter for the Text Widget. How do I show validation errors? Just as you would with a “hint”, pass an InputDecoration object to the decoration constructor for the Text widget. However, you don’t want to start off by showing an error. Instead, when the user has entered invalid data, update the state, and pass a new InputDecoration object. Flutter plugins How do I access the GPS sensor? Use the geolocator community plugin. How do I access the camera? The image_picker plugin is popular for accessing the camera. How do I log in with Facebook?
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-44
How do I log in with Facebook? To Log in with Facebook, use the flutter_facebook_login community plugin. How do I use Firebase features? Most Firebase functions are covered by first party plugins. These plugins are first-party integrations, maintained by the Flutter team: firebase_admob for Firebase AdMob firebase_analytics for Firebase Analytics firebase_auth for Firebase Auth firebase_database for Firebase RTDB firebase_storage for Firebase Cloud Storage firebase_messaging for Firebase Messaging (FCM) flutter_firebase_ui for quick Firebase Auth integrations (Facebook, Google, Twitter and email) cloud_firestore for Firebase Cloud Firestore You can also find some third-party Firebase plugins on pub.dev that cover areas not directly covered by the first-party plugins.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-45
How do I build my own custom native integrations? If there is platform-specific functionality that Flutter or its community Plugins are missing, you can build your own following the developing packages and plugins page. Flutter’s plugin architecture, in a nutshell, is much like using an Event bus in Android: you fire off a message and let the receiver process and emit a result back to you. In this case, the receiver is code running on the native side on Android or iOS. How do I use the NDK in my Flutter application? If you use the NDK in your current Android application and want your Flutter application to take advantage of your native libraries then it’s possible by building a custom plugin. Your custom plugin first talks to your Android app, where you call your native functions over JNI. Once a response is ready, send a message back to Flutter and render the result. Calling native code directly from Flutter is currently not supported. Themes
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-46
Themes How do I theme my app? Out of the box, Flutter comes with a beautiful implementation of Material Design, which takes care of a lot of styling and theming needs that you would typically do. Unlike Android where you declare themes in XML and then assign it to your application using AndroidManifest.xml, in Flutter you declare themes in the top level widget. To take full advantage of Material Components in your app, you can declare a top level widget MaterialApp as the entry point to your application. MaterialApp is a convenience widget that wraps a number of widgets that are commonly required for applications implementing Material Design. It builds upon a WidgetsApp by adding Material specific functionality. You can also use a WidgetsApp as your app widget, which provides some of the same functionality, but is not as rich as MaterialApp.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-47
To customize the colors and styles of any child components, pass a ThemeData object to the MaterialApp widget. For example, in the code below, the primary swatch is set to blue and text selection color is red. Databases and local storage How do I access Shared Preferences? In Android, you can store a small collection of key-value pairs using the SharedPreferences API. In Flutter, access this functionality using the Shared_Preferences plugin. This plugin wraps the functionality of both Shared Preferences and NSUserDefaults (the iOS equivalent). How do I access SQLite in Flutter? In Android, you use SQLite to store structured data that you can query using SQL. In Flutter, access this functionality using the SQFlite plugin. Debugging What tools can I use to debug my app in Flutter? Use the DevTools suite for debugging Flutter or Dart apps.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
04032aa23bfa-48
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. Notifications How do I set up push notifications? In Android, you use Firebase Cloud Messaging to setup push notifications for your app. In Flutter, access this functionality using the Firebase Messaging plugin. For more information on using the Firebase Cloud Messaging API, see the firebase_messaging plugin documentation.
https://docs.flutter.dev/get-started/flutter-for/android-devs/index.html
4fc361a64918-0
Introduction to declarative UI Why a declarative UI? How to change UI in a declarative framework This introduction describes the conceptual difference between the declarative style used by Flutter, and the imperative style used by many other UI frameworks. Why a declarative UI? Frameworks from Win32 to web to Android and iOS typically use an imperative style of UI programming. This might be the style you’re most familiar with—where you manually construct a full-functioned UI entity, such as a UIView or equivalent, and later mutate it using methods and setters when the UI changes. In order to lighten the burden on developers from having to program how to transition between various UI states, Flutter, by contrast, lets the developer describe the current UI state and leaves the transitioning to the framework. This, however, requires a slight shift in thinking for how to manipulate UI. How to change UI in a declarative framework
https://docs.flutter.dev/get-started/flutter-for/declarative/index.html
4fc361a64918-1
How to change UI in a declarative framework Consider a simplified example below: In the imperative style, you would typically go to ViewB’s owner and retrieve the instance b using selectors or with findViewById or similar, and invoke mutations on it (and implicitly invalidate it). For example: // Imperative style setColor red clearChildren () ViewC c3 new ViewC (...) add c3 You might also need to replicate this configuration in the constructor of ViewB since the source of truth for the UI might outlive instance b itself.
https://docs.flutter.dev/get-started/flutter-for/declarative/index.html
4fc361a64918-2
In the declarative style, view configurations (such as Flutter’s Widgets) are immutable and are only lightweight “blueprints”. To change the UI, a widget triggers a rebuild on itself (most commonly by calling setState() on StatefulWidgets in Flutter) and constructs a new Widget subtree. Here, rather than mutating an old instance b when the UI changes, Flutter constructs new Widget instances. The framework manages many of the responsibilities of a traditional UI object (such as maintaining the state of the layout) behind the scenes with RenderObjects. RenderObjects persist between frames and Flutter’s lightweight Widgets tell the framework to mutate the RenderObjects between states. The Flutter framework handles the rest.
https://docs.flutter.dev/get-started/flutter-for/declarative/index.html
b16dc750a3a9-0
Flutter for React Native developers Introduction to Dart for JavaScript Developers Entry point Printing to the console Variables Creating and assigning variables Default value Checking for null or zero Functions Asynchronous programming Futures async and await The basics How do I create a Flutter app? How do I run my app? How do I import widgets? What is the equivalent of the React Native “Hello world!” app in Flutter? How do I use widgets and nest them to form a widget tree? How do I create reusable components? Project structure and resources Where do I start writing the code? How are files structured in a Flutter app? Where do I put my resources and assets and how do I use them? How do I load images over a network? How do I install packages and package plugins? Flutter widgets Views
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-1
Flutter widgets Views What is the equivalent of the View container? What is the equivalent of FlatList or SectionList? How do I use a Canvas to draw or paint? Layouts How do I use widgets to define layout properties? How do I layer widgets? Styling How do I style my components? How do I use Icons and Colors? How do I add style themes? State management The StatelessWidget The StatefulWidget What are the StatefulWidget and StatelessWidget best practices? Props Local storage How do I store persistent key-value pairs that are global to the app? Routing How do I navigate between screens? How do I use tab navigation and drawer navigation? Tab navigation Drawer navigation Gesture detection and touch event handling
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-2
Tab navigation Drawer navigation Gesture detection and touch event handling How do I add a click or press listeners to a widget? Making HTTP network requests How do I fetch data from API calls? Form input How do I use text field widgets? How do I use Form widgets? Platform-specific code Debugging What tools can I use to debug my app in Flutter? How do I perform a hot reload? How do I access the in-app developer menu? Animation How do I add a simple fade-in animation? How do I add swipe animation to cards? React Native and Flutter widget equivalent components
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-3
React Native and Flutter widget equivalent components This document is for 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.
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-4
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. Try it out in DartPad. Printing to the console To print to the console in Dart, use print(). // JavaScript console log Hello world! );
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-5
log Hello world! ); Try it out in DartPad. 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 Try it out in DartPad. For more information, see Dart’s Type System. Default value In JavaScript, uninitialized variables are undefined.
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-6
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. Note: As of 2.12, Dart supports Sound Null Safety, all underlying types are non-nullable by default, which must be initialized as a non-nullable value. // JavaScript var name // == undefined Try it out in DartPad. For more information, see the documentation on variables. Checking for null or zero In JavaScript, values of 1 or any non-null objects are treated as true when using the == comparison operator. // JavaScript var myNull null if myNull
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-7
null if myNull console log null is treated as false ); var zero if zero console log 0 is treated as false ); In Dart, only the boolean value true is treated as true. Try it out in DartPad. Functions Dart and JavaScript functions are generally similar. The primary difference is the declaration. // JavaScript function fn () return true Try it out in DartPad. For more information, see the documentation on functions. Asynchronous programming Futures
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-8
Asynchronous programming Futures Like JavaScript, Dart supports single-threaded execution. In JavaScript, the Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Dart uses Future objects to handle this. // JavaScript class Example _getIPAddress () const url https://httpbin.org/ip return fetch url then response => response json ()) then responseJson => const ip responseJson origin return ip }); function
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-9
return ip }); function main () const example new Example (); example _getIPAddress () then ip => console log ip )) catch error => console error error )); main (); For more information, see the documentation on Future objects. async and await The async function declaration defines an asynchronous function. In JavaScript, the async function returns a Promise. The await operator is used to wait for a Promise.
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-10
// JavaScript class Example async function _getIPAddress () const url https://httpbin.org/ip const response await fetch url ); const json await response json (); const data json origin return data async function main () const example new Example (); try const ip
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-11
(); try const ip await example _getIPAddress (); console log ip ); catch error console error error ); main (); In Dart, an async function returns a Future, and the body of the function is scheduled for execution later. The await operator is used to wait for a Future. For more information, see the documentation for async and await. The basics How do I create a Flutter app? To create an app using React Native, you would run create-react-native-app from the command line. create-react-native-app <projectname>
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-12
create-react-native-app <projectname> To create an app in Flutter, do one of the following: Use an IDE with the Flutter and Dart plugins installed. Use the flutter create command from the command line. Make sure that the Flutter SDK is in your PATH. flutter create <projectname> For more information, see Getting started, which walks you through creating a button-click counter app. Creating a Flutter project builds all the files that you need to run a sample app on both Android and iOS devices. How do I run my app? In React Native, you would run npm run or yarn run from the project directory. You can run Flutter apps in a couple of ways: Use the “run” option in an IDE with the Flutter and Dart plugins. Use flutter run from the project’s root directory.
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-13
Use flutter run from the project’s root directory. Your app runs on a connected device, the iOS simulator, or the Android emulator. For more information, see the Flutter Getting started documentation. How do I import widgets? In React Native, you need to import each required component. // React Native import React from react import StyleSheet Text View from react-native In Flutter, to use widgets from the Material Design library, import the material.dart package. To use iOS style widgets, import the Cupertino library. To use a more basic widget set, import the Widgets library. Or, you can write your own widget library and import that.
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-14
Whichever widget package you import, Dart pulls in only the widgets that are used in your app. For more information, see the Flutter Widget Catalog. What is the equivalent of the React Native “Hello world!” app in Flutter? In React Native, the HelloWorldApp class extends React.Component and implements the render method by returning a view component. // React Native import React from react import StyleSheet Text View from react-native export default class App extends React Component render () return View style styles container
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-15
View style styles container Text Hello world !< /Text /View ); const styles StyleSheet create ({ container flex backgroundColor #fff alignItems center justifyContent center }); In Flutter, you can create an identical “Hello world!” app using the Center and Text widgets from the core widget library. The Center widget becomes the root of the widget tree and has one child, the Text widget. The following images show the Android and iOS UI for the basic Flutter “Hello world!” app.
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-16
Now that you’ve seen the most basic Flutter app, the next section shows how to take advantage of Flutter’s rich widget libraries to create a modern, polished app. How do I use widgets and nest them to form a widget tree? In Flutter, almost everything is a widget. Widgets are the basic building blocks of an app’s user interface. You compose widgets into a hierarchy, called a widget tree. Each widget nests inside a parent widget and inherits properties from its parent. Even the application object itself is a widget. There is no separate “application” object. Instead, the root widget serves this role. A widget can define: A structural element—like a button or menu A stylistic element—like a font or color scheme An aspect of layout—like padding or alignment
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-17
An aspect of layout—like padding or alignment The following example shows the “Hello world!” app using widgets from the Material library. In this example, the widget tree is nested inside the MaterialApp root widget. The following images show “Hello world!” built from Material Design widgets. You get more functionality for free than in the basic “Hello world!” app. When writing an app, you’ll use two types of widgets: StatelessWidget or StatefulWidget. A StatelessWidget is just what it sounds like—a widget with no state. A StatelessWidget is created once, and never changes its appearance. A StatefulWidget dynamically changes state based on data received, or user input. 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.
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-18
In simple or basic apps it’s easy to nest widgets, but as the code base gets larger and the app becomes complex, you should break deeply nested widgets into functions that return the widget or smaller classes. Creating separate functions and widgets allows you to reuse the components within the app. How do I create reusable components? In React Native, you would define a class to create a reusable component and then use props methods to set or return properties and values of the selected elements. In the example below, the CustomCard class is defined and then used inside a parent class. // React Native class CustomCard extends React Component render () return View Text Card this props index /Text Button
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-19
index /Text Button title Press onPress {() => this props onPress this props index )} /View ); // Usage CustomCard onPress this onPress index item key In Flutter, define a class to create a custom widget and then reuse the widget. You can also define and call a function that returns a reusable widget as shown in the build function in the following example. In the previous example, the constructor for the CustomCard class uses Dart’s curly brace syntax { } to indicate named parameters.
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html
b16dc750a3a9-20
To require these fields, either remove the curly braces from the constructor, or add required to the constructor. The following screenshots show an example of the reusable CustomCard class. Project structure and resources Where do I start writing the code? Start with the lib/main.dart file. It’s autogenerated when you create a Flutter app. In Flutter, the entry point file is {project_name}/lib/main.dart and execution starts from the main function. How are files structured in a Flutter app? When you create a new Flutter project, it builds the following directory structure. You can customize it later, but this is where you start. Where do I put my resources and assets and how do I use them? A Flutter resource or asset is a file that is bundled and deployed with your app and is accessible at runtime. Flutter apps can include the following asset types:
https://docs.flutter.dev/get-started/flutter-for/react-native-devs/index.html