File size: 32,876 Bytes
1755e21 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 |
<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> |