| <topic_start> |
| flutter for android developers |
| this document is meant for android developers looking to apply their |
| existing android knowledge to build mobile apps with flutter. |
| if you understand the fundamentals of the android framework then you |
| can use this document as a jump start to flutter development. |
| info 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. |
| <topic_end> |
| <topic_start> |
| views |
| <topic_end> |
| <topic_start> |
| what is the equivalent of a view in flutter? |
| how is react-style, or declarative, programming different than the |
| traditional imperative style? |
| for a comparison, see introduction to declarative UI. |
| in android, the view is the foundation of everything that shows up on the |
| screen. buttons, toolbars, and inputs, everything is a view. |
| in flutter, the rough equivalent to a view is a widget. |
| widgets don’t map exactly to android views, but while you’re getting |
| acquainted with how flutter works you can think of them as |
| “the way you declare and construct UI”. |
| however, these have a few differences to a view. to start, widgets have a |
| different lifespan: they are immutable and only exist until they need to be |
| changed. whenever widgets or their state change, flutter’s framework creates |
| a new tree of widget instances. in comparison, an android view is drawn once |
| and does not redraw until invalidate is called. |
| flutter’s widgets are lightweight, in part due to their immutability. |
| because they aren’t views themselves, and aren’t directly drawing anything, |
| but rather are a description of the UI and its semantics that get “inflated” |
| into actual view objects under the hood. |
| flutter includes the material components library. |
| these are widgets that implement the |
| material design guidelines. material design is a |
| flexible design system optimized for all platforms, |
| including iOS. |
| but flutter is flexible and expressive enough to implement any design language. |
| for example, on iOS, you can use the cupertino widgets |
| to produce an interface that looks like apple’s iOS design language. |
| <topic_end> |
| <topic_start> |
| 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. |
| this is where the concept of stateful and stateless widgets comes from. |
| a StatelessWidget is just what it sounds like—a |
| widget with no state information. |
| StatelessWidgets are useful when the part of the user interface |
| you are describing does not depend on anything other than the configuration |
| information in the object. |
| for example, in android, this is similar to placing an ImageView |
| with your logo. the logo is not going to change during runtime, |
| so use a StatelessWidget in flutter. |
| if you want to dynamically change the UI based on data received |
| after making an HTTP call or user interaction then you have to work |
| with StatefulWidget and tell the flutter framework that the widget’s |
| state has been updated so it can update that widget. |
| the important thing to note here is at the core both stateless and stateful |
| widgets behave the same. they rebuild every frame, the difference is the |
| StatefulWidget has a state object that stores state data across frames |
| and restores it. |
| if you are in doubt, then always remember this rule: if a widget changes |
| (because of user interactions, for example) it’s stateful. |
| however, if a widget reacts to change, the containing parent widget can |
| still be stateless if it doesn’t itself react to change. |
| the following example shows how to use a StatelessWidget. a common |
| StatelessWidget is the text widget. if you look at the implementation of |
| the text widget you’ll find that it subclasses StatelessWidget. |
| <code_start> |
| text( |
| 'i like flutter!', |
| style: TextStyle(fontWeight: FontWeight.bold), |
| ); |
| <code_end> |
| 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: |
| <code_start> |
| import 'package:flutter/material.dart'; |
| void main() { |
| runApp(const SampleApp()); |
| } |
| class SampleApp extends StatelessWidget { |
| const SampleApp({super.key}); |
| // this widget is the root of your application. |
| @override |
| widget build(BuildContext context) { |
| return MaterialApp( |
| title: 'sample app', |
| theme: ThemeData( |
| colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), |
| ), |
| home: const SampleAppPage(), |
| ); |
| } |
| } |
| class SampleAppPage extends StatefulWidget { |
| const SampleAppPage({super.key}); |
| @override |
| State<SampleAppPage> createState() => _SampleAppPageState(); |
| } |
| class _SampleAppPageState extends State<SampleAppPage> { |
| // default placeholder text. |
| string textToShow = 'i like flutter'; |
| void _updateText() { |
| setState(() { |
| // update the text. |
| textToShow = 'flutter is awesome!'; |
| }); |
| } |
| @override |
| widget build(BuildContext context) { |
| return scaffold( |
| appBar: AppBar( |
| title: const Text('Sample app'), |
| ), |
| body: center(child: Text(textToShow)), |
| floatingActionButton: FloatingActionButton( |
| onPressed: _updateText, |
| tooltip: 'update text', |
| child: const Icon(Icons.update), |
| ), |
| ); |
| } |
| } |
| <code_end> |
| <topic_end> |
| <topic_start> |
| 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: |
| <code_start> |
| @override |
| widget build(BuildContext context) { |
| return scaffold( |
| appBar: AppBar( |
| title: const Text('Sample app'), |
| ), |
| body: center( |
| child: ElevatedButton( |
| style: ElevatedButton.styleFrom( |
| padding: const EdgeInsets.only(left: 20, right: 30), |
| ), |
| onPressed: () {}, |
| child: const Text('Hello'), |
| ), |
| ), |
| ); |
| } |
| <code_end> |
| you can view some of the layouts that flutter has to offer in the |
| widget catalog. |
| <topic_end> |
| <topic_start> |
| 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: |
| <code_start> |
| import 'package:flutter/material.dart'; |
| void main() { |
| runApp(const SampleApp()); |
| } |
| class SampleApp extends StatelessWidget { |
| const SampleApp({super.key}); |
| // this widget is the root of your application. |
| @override |
| widget build(BuildContext context) { |
| return MaterialApp( |
| title: 'sample app', |
| theme: ThemeData( |
| colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), |
| ), |
| home: const SampleAppPage(), |
| ); |
| } |
| } |
| class SampleAppPage extends StatefulWidget { |
| const SampleAppPage({super.key}); |
| @override |
| State<SampleAppPage> createState() => _SampleAppPageState(); |
| } |
| class _SampleAppPageState extends State<SampleAppPage> { |
| // default value for toggle. |
| bool toggle = true; |
| void _toggle() { |
| setState(() { |
| toggle = !toggle; |
| }); |
| } |
| widget _getToggleChild() { |
| if (toggle) { |
| return const Text('Toggle one'); |
| } else { |
| return ElevatedButton( |
| onPressed: () {}, |
| child: const Text('Toggle two'), |
| ); |
| } |
| } |
| @override |
| widget build(BuildContext context) { |
| return scaffold( |
| appBar: AppBar( |
| title: const Text('Sample app'), |
| ), |
| body: center( |
| child: _getToggleChild(), |
| ), |
| floatingActionButton: FloatingActionButton( |
| onPressed: _toggle, |
| tooltip: 'update text', |
| child: const Icon(Icons.update), |
| ), |
| ); |
| } |
| } |
| <code_end> |
| <topic_end> |
| <topic_start> |
| 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. |
| 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: |
| <code_start> |
| import 'package:flutter/material.dart'; |
| void main() { |
| runApp(const FadeAppTest()); |
| } |
| class FadeAppTest extends StatelessWidget { |
| const FadeAppTest({super.key}); |
| // this widget is the root of your application. |
| @override |
| widget build(BuildContext context) { |
| return MaterialApp( |
| title: 'fade demo', |
| theme: ThemeData( |
| colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), |
| ), |
| home: const MyFadeTest(title: 'fade demo'), |
| ); |
| } |
| } |
| class MyFadeTest extends StatefulWidget { |
| const MyFadeTest({super.key, required this.title}); |
| final string title; |
| @override |
| State<MyFadeTest> createState() => _MyFadeTest(); |
| } |
| class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin { |
| late AnimationController controller; |
| late CurvedAnimation curve; |
| @override |
| void initState() { |
| super.initState(); |
| controller = AnimationController( |
| duration: const duration(milliseconds: 2000), |
| vsync: this, |
| ); |
| curve = CurvedAnimation( |
| parent: controller, |
| curve: Curves.easeIn, |
| ); |
| } |
| @override |
| widget build(BuildContext context) { |
| return scaffold( |
| appBar: AppBar( |
| title: text(widget.title), |
| ), |
| body: center( |
| child: FadeTransition( |
| opacity: curve, |
| child: const FlutterLogo( |
| size: 100, |
| ), |
| ), |
| ), |
| floatingActionButton: FloatingActionButton( |
| tooltip: 'fade', |
| onPressed: () { |
| controller.forward(); |
| }, |
| child: const Icon(Icons.brush), |
| ), |
| ); |
| } |
| } |
| <code_end> |
| for more information, see |
| animation & motion widgets, |
| the animations tutorial, |
| and the animations overview. |
| <topic_end> |
| <topic_start> |
| 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’s 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. |
| to learn how to implement a signature painter in flutter, |
| see collin’s answer on custom paint. |
| <code_start> |
| import 'package:flutter/material.dart'; |
| void main() => runApp(const MaterialApp(home: DemoApp())); |
| class DemoApp extends StatelessWidget { |
| const DemoApp({super.key}); |
| @override |
| widget build(BuildContext context) => const scaffold(body: signature()); |
| } |
| class signature extends StatefulWidget { |
| const signature({super.key}); |
| @override |
| SignatureState createState() => SignatureState(); |
| } |
| class SignatureState extends State<Signature> { |
| List<Offset?> _points = <offset>[]; |
| @override |
| widget build(BuildContext context) { |
| return GestureDetector( |
| onPanUpdate: (details) { |
| setState(() { |
| RenderBox? referenceBox = context.findRenderObject() as RenderBox; |
| offset localPosition = |
| referenceBox.globalToLocal(details.globalPosition); |
| _points = List.from(_points)..add(localPosition); |
| }); |
| }, |
| onPanEnd: (details) => _points.add(null), |
| child: CustomPaint( |
| painter: SignaturePainter(_points), |
| size: size.infinite, |
| ), |
| ); |
| } |
| } |
| class SignaturePainter extends CustomPainter { |
| SignaturePainter(this.points); |
| final List<Offset?> points; |
| @override |
| void paint(Canvas canvas, size size) { |
| var paint = paint() |
| ..color = colors.black |
| ..strokeCap = StrokeCap.round |
| ..strokeWidth = 5; |
| 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; |
| } |
| <code_end> |
| <topic_end> |
| <topic_start> |
| 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: |
| <code_start> |
| class CustomButton extends StatelessWidget { |
| final string label; |
| const CustomButton(this.label, {super.key}); |
| @override |
| widget build(BuildContext context) { |
| return ElevatedButton( |
| onPressed: () {}, |
| child: text(label), |
| ); |
| } |
| } |
| <code_end> |
| then use CustomButton, just as you’d use any other flutter widget: |
| <code_start> |
| @override |
| widget build(BuildContext context) { |
| return const center( |
| child: CustomButton('Hello'), |
| ); |
| } |
| <code_end> |
| <topic_end> |
| <topic_start> |
| intents |
| <topic_end> |
| <topic_start> |
| 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”. |
| in android, you declare your activities inside the app’s AndroidManifest.xml. |
| in flutter, you have a couple options to navigate between pages: |
| the following example builds a map. |
| <code_start> |
| void main() { |
| runApp(MaterialApp( |
| home: const MyAppHome(), // becomes the route named '/'. |
| routes: <string, WidgetBuilder>{ |
| '/a': (context) => const MyPage(title: 'page a'), |
| '/b': (context) => const MyPage(title: 'page b'), |
| '/c': (context) => const MyPage(title: 'page c'), |
| }, |
| )); |
| } |
| <code_end> |
| navigate to a route by pushing its name to the navigator. |
| <code_start> |
| Navigator.of(context).pushNamed('/b'); |
| <code_end> |
| 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. |
| <topic_end> |
| <topic_start> |
| 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. |
| 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: |
| 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: |
| finally, request the data from the flutter side |
| when the widget is rendered: |
| <code_start> |
| import 'package:flutter/material.dart'; |
| import 'package:flutter/services.dart'; |
| void main() { |
| runApp(const SampleApp()); |
| } |
| class SampleApp extends StatelessWidget { |
| const SampleApp({super.key}); |
| // this widget is the root of your application. |
| @override |
| widget build(BuildContext context) { |
| return MaterialApp( |
| title: 'sample shared app handler', |
| theme: ThemeData( |
| colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), |
| ), |
| home: const SampleAppPage(), |
| ); |
| } |
| } |
| class SampleAppPage extends StatefulWidget { |
| const SampleAppPage({super.key}); |
| @override |
| State<SampleAppPage> createState() => _SampleAppPageState(); |
| } |
| class _SampleAppPageState extends State<SampleAppPage> { |
| static const platform = MethodChannel('app.channel.shared.data'); |
| string dataShared = 'no data'; |
| @override |
| void initState() { |
| super.initState(); |
| getSharedText(); |
| } |
| @override |
| widget build(BuildContext context) { |
| return scaffold(body: center(child: Text(dataShared))); |
| } |
| future<void> getSharedText() async { |
| var sharedData = await platform.invokeMethod('getSharedText'); |
| if (shareddata != null) { |
| setState(() { |
| dataShared = sharedData; |
| }); |
| } |
| } |
| } |
| <code_end> |
| <topic_end> |
| <topic_start> |
| 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(). |
| for example, to start a location route that lets the user select |
| their location, you could do the following: |
| <code_start> |
| object? coordinates = await Navigator.of(context).pushNamed('/location'); |
| <code_end> |
| and then, inside your location route, once the user has selected their location |
| you can pop the stack with the result: |
| <code_start> |
| navigator.of(context).pop({'lat': 43.821757, 'long': -79.226392}); |
| <code_end> |
| <topic_end> |
| <topic_start> |
| async UI |
| <topic_end> |
| <topic_start> |
| 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. |
| 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: |
| <code_start> |
| future<void> loadData() async { |
| var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts'); |
| http.Response response = await http.get(dataURL); |
| setState(() { |
| widgets = jsonDecode(response.body); |
| }); |
| } |
| <code_end> |
| once the awaited network call is done, update the UI by calling setState(), |
| which triggers a rebuild of the widget subtree and updates the data. |
| the following example loads data asynchronously and displays it in a ListView: |
| <code_start> |
| import 'dart:convert'; |
| import 'package:flutter/material.dart'; |
| import 'package:http/http.dart' as http; |
| void main() { |
| runApp(const SampleApp()); |
| } |
| class SampleApp extends StatelessWidget { |
| const SampleApp({super.key}); |
| @override |
| widget build(BuildContext context) { |
| return MaterialApp( |
| title: 'sample app', |
| theme: ThemeData( |
| colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), |
| ), |
| home: const SampleAppPage(), |
| ); |
| } |
| } |
| class SampleAppPage extends StatefulWidget { |
| const SampleAppPage({super.key}); |
| @override |
| State<SampleAppPage> createState() => _SampleAppPageState(); |
| } |
| class _SampleAppPageState extends State<SampleAppPage> { |
| list widgets = []; |
| @override |
| void initState() { |
| super.initState(); |
| loadData(); |
| } |
| @override |
| widget build(BuildContext context) { |
| return scaffold( |
| appBar: AppBar( |
| title: const Text('Sample app'), |
| ), |
| body: ListView.builder( |
| itemCount: widgets.length, |
| itemBuilder: (context, position) { |
| return getRow(position); |
| }, |
| ), |
| ); |
| } |
| widget getRow(int i) { |
| return padding( |
| padding: const EdgeInsets.all(10), |
| child: Text("Row ${widgets[i]["title"]}"), |
| ); |
| } |
| future<void> loadData() async { |
| var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts'); |
| http.Response response = await http.get(dataURL); |
| setState(() { |
| widgets = jsonDecode(response.body); |
| }); |
| } |
| } |
| <code_end> |
| refer to the next section for more information on doing work in the |
| background, and how flutter differs from android. |
| <topic_end> |
| <topic_start> |
| 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. |
| for I/O-bound work, declare the function as an async function, |
| and await on long-running tasks inside the function: |
| <code_start> |
| future<void> loadData() async { |
| var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts'); |
| http.Response response = await http.get(dataURL); |
| setState(() { |
| widgets = jsonDecode(response.body); |
| }); |
| } |
| <code_end> |
| 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. |
| 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. |
| <code_start> |
| future<void> loadData() async { |
| ReceivePort receivePort = ReceivePort(); |
| await Isolate.spawn(dataLoader, receivePort.sendPort); |
| // the 'echo' isolate sends its SendPort as the first message. |
| SendPort sendPort = await receivePort.first; |
| list msg = await sendReceive( |
| sendPort, |
| 'https://jsonplaceholder.typicode.com/posts', |
| ); |
| setState(() { |
| widgets = msg; |
| }); |
| } |
| // the entry point for the isolate. |
| static future<void> dataLoader(SendPort sendPort) async { |
| // open the ReceivePort for incoming messages. |
| ReceivePort port = ReceivePort(); |
| // notify any other isolates what port this isolate listens to. |
| sendPort.send(port.sendPort); |
| await for (var msg in port) { |
| string data = msg[0]; |
| SendPort replyTo = msg[1]; |
| string dataURL = data; |
| http.Response response = await http.get(Uri.parse(dataURL)); |
| // lots of JSON to parse |
| replyTo.send(jsonDecode(response.body)); |
| } |
| } |
| future sendReceive(SendPort port, msg) { |
| ReceivePort response = ReceivePort(); |
| port.send([msg, response.sendPort]); |
| return response.first; |
| } |
| <code_end> |
| 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: |
| <code_start> |
| import 'dart:async'; |
| import 'dart:convert'; |
| import 'dart:isolate'; |
| import 'package:flutter/material.dart'; |
| import 'package:http/http.dart' as http; |
| void main() { |
| runApp(const SampleApp()); |
| } |
| class SampleApp extends StatelessWidget { |
| const SampleApp({super.key}); |
| @override |
| widget build(BuildContext context) { |
| return MaterialApp( |
| title: 'sample app', |
| theme: ThemeData( |
| colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), |
| ), |
| home: const SampleAppPage(), |
| ); |
| } |
| } |
| class SampleAppPage extends StatefulWidget { |
| const SampleAppPage({super.key}); |
| @override |
| State<SampleAppPage> createState() => _SampleAppPageState(); |
| } |
| class _SampleAppPageState extends State<SampleAppPage> { |
| list widgets = []; |
| @override |
| void initState() { |
| super.initState(); |
| loadData(); |
| } |
| widget getBody() { |
| bool showLoadingDialog = widgets.isEmpty; |
| if (showloadingdialog) { |
| return getProgressDialog(); |
| } else { |
| return getListView(); |
| } |
| } |
| widget getProgressDialog() { |
| return const center(child: CircularProgressIndicator()); |
| } |
| @override |
| widget build(BuildContext context) { |
| return scaffold( |
| appBar: AppBar( |
| title: const Text('Sample app'), |
| ), |
| body: getBody(), |
| ); |
| } |
| ListView getListView() { |
| return ListView.builder( |
| itemCount: widgets.length, |
| itemBuilder: (context, position) { |
| return getRow(position); |
| }, |
| ); |
| } |
| widget getRow(int i) { |
| return padding( |
| padding: const EdgeInsets.all(10), |
| child: Text("Row ${widgets[i]["title"]}"), |
| ); |
| } |
| future<void> loadData() async { |
| ReceivePort receivePort = ReceivePort(); |
| await Isolate.spawn(dataLoader, receivePort.sendPort); |
| // the 'echo' isolate sends its SendPort as the first message. |
| SendPort sendPort = await receivePort.first; |
| list msg = await sendReceive( |
| sendPort, |
| 'https://jsonplaceholder.typicode.com/posts', |
| ); |
| setState(() { |
| widgets = msg; |
| }); |
| } |
| // the entry point for the isolate. |
| static future<void> dataLoader(SendPort sendPort) async { |
| // open the ReceivePort for incoming messages. |
| ReceivePort port = ReceivePort(); |
| // notify any other isolates what port this isolate listens to. |
| sendPort.send(port.sendPort); |
| await for (var msg in port) { |
| string data = msg[0]; |
| SendPort replyTo = msg[1]; |
| string dataURL = data; |
| http.Response response = await http.get(Uri.parse(dataURL)); |
| // lots of JSON to parse |
| replyTo.send(jsonDecode(response.body)); |
| } |
| } |
| future sendReceive(SendPort port, msg) { |
| ReceivePort response = ReceivePort(); |
| port.send([msg, response.sendPort]); |
| return response.first; |
| } |
| } |
| <code_end> |
| <topic_end> |
| <topic_start> |
| what is the equivalent of OkHttp on flutter? |
| making a network call in flutter is easy when you use the |
| popular http package. |
| 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 add the http package as a dependency, run flutter pub add: |
| to make a network call, call await on the async function http.get(): |
| <code_start> |
| import 'dart:developer' as developer; |
| import 'package:http/http.dart' as http; |
| future<void> loadData() async { |
| var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts'); |
| http.Response response = await http.get(dataURL); |
| developer.log(response.body); |
| } |
| <code_end> |
| <topic_end> |
| <topic_start> |
| 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. |
| 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. |
| <code_start> |
| import 'dart:convert'; |
| import 'package:flutter/material.dart'; |
| import 'package:http/http.dart' as http; |
| void main() { |
| runApp(const SampleApp()); |
| } |
| class SampleApp extends StatelessWidget { |
| const SampleApp({super.key}); |
| @override |
| widget build(BuildContext context) { |
| return MaterialApp( |
| title: 'sample app', |
| theme: ThemeData( |
| colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), |
| ), |
| home: const SampleAppPage(), |
| ); |
| } |
| } |
| class SampleAppPage extends StatefulWidget { |
| const SampleAppPage({super.key}); |
| @override |
| State<SampleAppPage> createState() => _SampleAppPageState(); |
| } |
| class _SampleAppPageState extends State<SampleAppPage> { |
| list widgets = []; |
| @override |
| void initState() { |
| super.initState(); |
| loadData(); |
| } |
| widget getBody() { |
| bool showLoadingDialog = widgets.isEmpty; |
| if (showloadingdialog) { |
| return getProgressDialog(); |
| } else { |
| return getListView(); |
| } |
| } |
| widget getProgressDialog() { |
| return const center(child: CircularProgressIndicator()); |
| } |
| @override |
| widget build(BuildContext context) { |
| return scaffold( |
| appBar: AppBar( |
| title: const Text('Sample app'), |
| ), |
| body: getBody(), |
| ); |
| } |
| ListView getListView() { |
| return ListView.builder( |
| itemCount: widgets.length, |
| itemBuilder: (context, position) { |
| return getRow(position); |
| }, |
| ); |
| } |
| widget getRow(int i) { |
| return padding( |
| padding: const EdgeInsets.all(10), |
| child: Text("Row ${widgets[i]["title"]}"), |
| ); |
| } |
| future<void> loadData() async { |
| var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts'); |
| http.Response response = await http.get(dataURL); |
| setState(() { |
| widgets = jsonDecode(response.body); |
| }); |
| } |
| } |
| <code_end> |
| <topic_end> |