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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<topic_start>
|
2 |
+
flutter for android developers
|
3 |
+
this document is meant for android developers looking to apply their
|
4 |
+
existing android knowledge to build mobile apps with flutter.
|
5 |
+
if you understand the fundamentals of the android framework then you
|
6 |
+
can use this document as a jump start to flutter development.
|
7 |
+
info note
|
8 |
+
to integrate flutter code into your android app, see
|
9 |
+
add flutter to existing app.
|
10 |
+
your android knowledge and skill set are highly valuable when building with
|
11 |
+
flutter, because flutter relies on the mobile operating system for numerous
|
12 |
+
capabilities and configurations. flutter is a new way to build UIs for mobile,
|
13 |
+
but it has a plugin system to communicate with android (and iOS) for non-UI
|
14 |
+
tasks. if you’re an expert with android, you don’t have to relearn everything
|
15 |
+
to use flutter.
|
16 |
+
this document can be used as a cookbook by jumping around and
|
17 |
+
finding questions that are most relevant to your needs.
|
18 |
+
<topic_end>
|
19 |
+
<topic_start>
|
20 |
+
views
|
21 |
+
<topic_end>
|
22 |
+
<topic_start>
|
23 |
+
what is the equivalent of a view in flutter?
|
24 |
+
how is react-style, or declarative, programming different than the
|
25 |
+
traditional imperative style?
|
26 |
+
for a comparison, see introduction to declarative UI.
|
27 |
+
in android, the view is the foundation of everything that shows up on the
|
28 |
+
screen. buttons, toolbars, and inputs, everything is a view.
|
29 |
+
in flutter, the rough equivalent to a view is a widget.
|
30 |
+
widgets don’t map exactly to android views, but while you’re getting
|
31 |
+
acquainted with how flutter works you can think of them as
|
32 |
+
“the way you declare and construct UI”.
|
33 |
+
however, these have a few differences to a view. to start, widgets have a
|
34 |
+
different lifespan: they are immutable and only exist until they need to be
|
35 |
+
changed. whenever widgets or their state change, flutter’s framework creates
|
36 |
+
a new tree of widget instances. in comparison, an android view is drawn once
|
37 |
+
and does not redraw until invalidate is called.
|
38 |
+
flutter’s widgets are lightweight, in part due to their immutability.
|
39 |
+
because they aren’t views themselves, and aren’t directly drawing anything,
|
40 |
+
but rather are a description of the UI and its semantics that get “inflated”
|
41 |
+
into actual view objects under the hood.
|
42 |
+
flutter includes the material components library.
|
43 |
+
these are widgets that implement the
|
44 |
+
material design guidelines. material design is a
|
45 |
+
flexible design system optimized for all platforms,
|
46 |
+
including iOS.
|
47 |
+
but flutter is flexible and expressive enough to implement any design language.
|
48 |
+
for example, on iOS, you can use the cupertino widgets
|
49 |
+
to produce an interface that looks like apple’s iOS design language.
|
50 |
+
<topic_end>
|
51 |
+
<topic_start>
|
52 |
+
how do i update widgets?
|
53 |
+
in android, you update your views by directly mutating them. however,
|
54 |
+
in flutter, widgets are immutable and are not updated directly,
|
55 |
+
instead you have to work with the widget’s state.
|
56 |
+
this is where the concept of stateful and stateless widgets comes from.
|
57 |
+
a StatelessWidget is just what it sounds like—a
|
58 |
+
widget with no state information.
|
59 |
+
StatelessWidgets are useful when the part of the user interface
|
60 |
+
you are describing does not depend on anything other than the configuration
|
61 |
+
information in the object.
|
62 |
+
for example, in android, this is similar to placing an ImageView
|
63 |
+
with your logo. the logo is not going to change during runtime,
|
64 |
+
so use a StatelessWidget in flutter.
|
65 |
+
if you want to dynamically change the UI based on data received
|
66 |
+
after making an HTTP call or user interaction then you have to work
|
67 |
+
with StatefulWidget and tell the flutter framework that the widget’s
|
68 |
+
state has been updated so it can update that widget.
|
69 |
+
the important thing to note here is at the core both stateless and stateful
|
70 |
+
widgets behave the same. they rebuild every frame, the difference is the
|
71 |
+
StatefulWidget has a state object that stores state data across frames
|
72 |
+
and restores it.
|
73 |
+
if you are in doubt, then always remember this rule: if a widget changes
|
74 |
+
(because of user interactions, for example) it’s stateful.
|
75 |
+
however, if a widget reacts to change, the containing parent widget can
|
76 |
+
still be stateless if it doesn’t itself react to change.
|
77 |
+
the following example shows how to use a StatelessWidget. a common
|
78 |
+
StatelessWidget is the text widget. if you look at the implementation of
|
79 |
+
the text widget you’ll find that it subclasses StatelessWidget.
|
80 |
+
<code_start>
|
81 |
+
text(
|
82 |
+
'i like flutter!',
|
83 |
+
style: TextStyle(fontWeight: FontWeight.bold),
|
84 |
+
);
|
85 |
+
<code_end>
|
86 |
+
as you can see, the text widget has no state information associated with it,
|
87 |
+
it renders what is passed in its constructors and nothing more.
|
88 |
+
but, what if you want to make “i like flutter” change dynamically, for
|
89 |
+
example when clicking a FloatingActionButton?
|
90 |
+
to achieve this, wrap the text widget in a StatefulWidget and
|
91 |
+
update it when the user clicks the button.
|
92 |
+
for example:
|
93 |
+
<code_start>
|
94 |
+
import 'package:flutter/material.dart';
|
95 |
+
void main() {
|
96 |
+
runApp(const SampleApp());
|
97 |
+
}
|
98 |
+
class SampleApp extends StatelessWidget {
|
99 |
+
const SampleApp({super.key});
|
100 |
+
// this widget is the root of your application.
|
101 |
+
@override
|
102 |
+
widget build(BuildContext context) {
|
103 |
+
return MaterialApp(
|
104 |
+
title: 'sample app',
|
105 |
+
theme: ThemeData(
|
106 |
+
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
|
107 |
+
),
|
108 |
+
home: const SampleAppPage(),
|
109 |
+
);
|
110 |
+
}
|
111 |
+
}
|
112 |
+
class SampleAppPage extends StatefulWidget {
|
113 |
+
const SampleAppPage({super.key});
|
114 |
+
@override
|
115 |
+
State<SampleAppPage> createState() => _SampleAppPageState();
|
116 |
+
}
|
117 |
+
class _SampleAppPageState extends State<SampleAppPage> {
|
118 |
+
// default placeholder text.
|
119 |
+
string textToShow = 'i like flutter';
|
120 |
+
void _updateText() {
|
121 |
+
setState(() {
|
122 |
+
// update the text.
|
123 |
+
textToShow = 'flutter is awesome!';
|
124 |
+
});
|
125 |
+
}
|
126 |
+
@override
|
127 |
+
widget build(BuildContext context) {
|
128 |
+
return scaffold(
|
129 |
+
appBar: AppBar(
|
130 |
+
title: const Text('Sample app'),
|
131 |
+
),
|
132 |
+
body: center(child: Text(textToShow)),
|
133 |
+
floatingActionButton: FloatingActionButton(
|
134 |
+
onPressed: _updateText,
|
135 |
+
tooltip: 'update text',
|
136 |
+
child: const Icon(Icons.update),
|
137 |
+
),
|
138 |
+
);
|
139 |
+
}
|
140 |
+
}
|
141 |
+
<code_end>
|
142 |
+
<topic_end>
|
143 |
+
<topic_start>
|
144 |
+
how do i lay out my widgets? where is my XML layout file?
|
145 |
+
in android, you write layouts in XML, but in flutter you write your layouts
|
146 |
+
with a widget tree.
|
147 |
+
the following example shows how to display a simple widget with padding:
|
148 |
+
<code_start>
|
149 |
+
@override
|
150 |
+
widget build(BuildContext context) {
|
151 |
+
return scaffold(
|
152 |
+
appBar: AppBar(
|
153 |
+
title: const Text('Sample app'),
|
154 |
+
),
|
155 |
+
body: center(
|
156 |
+
child: ElevatedButton(
|
157 |
+
style: ElevatedButton.styleFrom(
|
158 |
+
padding: const EdgeInsets.only(left: 20, right: 30),
|
159 |
+
),
|
160 |
+
onPressed: () {},
|
161 |
+
child: const Text('Hello'),
|
162 |
+
),
|
163 |
+
),
|
164 |
+
);
|
165 |
+
}
|
166 |
+
<code_end>
|
167 |
+
you can view some of the layouts that flutter has to offer in the
|
168 |
+
widget catalog.
|
169 |
+
<topic_end>
|
170 |
+
<topic_start>
|
171 |
+
how do i add or remove a component from my layout?
|
172 |
+
in android, you call addChild() or removeChild()
|
173 |
+
on a parent to dynamically add or remove child views.
|
174 |
+
in flutter, because widgets are immutable there is
|
175 |
+
no direct equivalent to addChild(). instead,
|
176 |
+
you can pass a function to the parent that returns a widget,
|
177 |
+
and control that child’s creation with a boolean flag.
|
178 |
+
for example, here is how you can toggle between two
|
179 |
+
widgets when you click on a FloatingActionButton:
|
180 |
+
<code_start>
|
181 |
+
import 'package:flutter/material.dart';
|
182 |
+
void main() {
|
183 |
+
runApp(const SampleApp());
|
184 |
+
}
|
185 |
+
class SampleApp extends StatelessWidget {
|
186 |
+
const SampleApp({super.key});
|
187 |
+
// this widget is the root of your application.
|
188 |
+
@override
|
189 |
+
widget build(BuildContext context) {
|
190 |
+
return MaterialApp(
|
191 |
+
title: 'sample app',
|
192 |
+
theme: ThemeData(
|
193 |
+
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
|
194 |
+
),
|
195 |
+
home: const SampleAppPage(),
|
196 |
+
);
|
197 |
+
}
|
198 |
+
}
|
199 |
+
class SampleAppPage extends StatefulWidget {
|
200 |
+
const SampleAppPage({super.key});
|
201 |
+
@override
|
202 |
+
State<SampleAppPage> createState() => _SampleAppPageState();
|
203 |
+
}
|
204 |
+
class _SampleAppPageState extends State<SampleAppPage> {
|
205 |
+
// default value for toggle.
|
206 |
+
bool toggle = true;
|
207 |
+
void _toggle() {
|
208 |
+
setState(() {
|
209 |
+
toggle = !toggle;
|
210 |
+
});
|
211 |
+
}
|
212 |
+
widget _getToggleChild() {
|
213 |
+
if (toggle) {
|
214 |
+
return const Text('Toggle one');
|
215 |
+
} else {
|
216 |
+
return ElevatedButton(
|
217 |
+
onPressed: () {},
|
218 |
+
child: const Text('Toggle two'),
|
219 |
+
);
|
220 |
+
}
|
221 |
+
}
|
222 |
+
@override
|
223 |
+
widget build(BuildContext context) {
|
224 |
+
return scaffold(
|
225 |
+
appBar: AppBar(
|
226 |
+
title: const Text('Sample app'),
|
227 |
+
),
|
228 |
+
body: center(
|
229 |
+
child: _getToggleChild(),
|
230 |
+
),
|
231 |
+
floatingActionButton: FloatingActionButton(
|
232 |
+
onPressed: _toggle,
|
233 |
+
tooltip: 'update text',
|
234 |
+
child: const Icon(Icons.update),
|
235 |
+
),
|
236 |
+
);
|
237 |
+
}
|
238 |
+
}
|
239 |
+
<code_end>
|
240 |
+
<topic_end>
|
241 |
+
<topic_start>
|
242 |
+
how do i animate a widget?
|
243 |
+
in android, you either create animations using XML, or call the animate()
|
244 |
+
method on a view. in flutter, animate widgets using the animation
|
245 |
+
library by wrapping widgets inside an animated widget.
|
246 |
+
in flutter, use an AnimationController which is an animation<double>
|
247 |
+
that can pause, seek, stop and reverse the animation. it requires a ticker
|
248 |
+
that signals when vsync happens, and produces a linear interpolation between
|
249 |
+
0 and 1 on each frame while it’s running. you then create one or more
|
250 |
+
animations and attach them to the controller.
|
251 |
+
for example, you might use CurvedAnimation to implement an animation
|
252 |
+
along an interpolated curve. in this sense, the controller
|
253 |
+
is the “master” source of the animation progress and the CurvedAnimation
|
254 |
+
computes the curve that replaces the controller’s default linear motion.
|
255 |
+
like widgets, animations in flutter work with composition.
|
256 |
+
when building the widget tree you assign the animation to an animated
|
257 |
+
property of a widget, such as the opacity of a FadeTransition, and tell the
|
258 |
+
controller to start the animation.
|
259 |
+
the following example shows how to write a FadeTransition that fades the
|
260 |
+
widget into a logo when you press the FloatingActionButton:
|
261 |
+
<code_start>
|
262 |
+
import 'package:flutter/material.dart';
|
263 |
+
void main() {
|
264 |
+
runApp(const FadeAppTest());
|
265 |
+
}
|
266 |
+
class FadeAppTest extends StatelessWidget {
|
267 |
+
const FadeAppTest({super.key});
|
268 |
+
// this widget is the root of your application.
|
269 |
+
@override
|
270 |
+
widget build(BuildContext context) {
|
271 |
+
return MaterialApp(
|
272 |
+
title: 'fade demo',
|
273 |
+
theme: ThemeData(
|
274 |
+
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
|
275 |
+
),
|
276 |
+
home: const MyFadeTest(title: 'fade demo'),
|
277 |
+
);
|
278 |
+
}
|
279 |
+
}
|
280 |
+
class MyFadeTest extends StatefulWidget {
|
281 |
+
const MyFadeTest({super.key, required this.title});
|
282 |
+
final string title;
|
283 |
+
@override
|
284 |
+
State<MyFadeTest> createState() => _MyFadeTest();
|
285 |
+
}
|
286 |
+
class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin {
|
287 |
+
late AnimationController controller;
|
288 |
+
late CurvedAnimation curve;
|
289 |
+
@override
|
290 |
+
void initState() {
|
291 |
+
super.initState();
|
292 |
+
controller = AnimationController(
|
293 |
+
duration: const duration(milliseconds: 2000),
|
294 |
+
vsync: this,
|
295 |
+
);
|
296 |
+
curve = CurvedAnimation(
|
297 |
+
parent: controller,
|
298 |
+
curve: Curves.easeIn,
|
299 |
+
);
|
300 |
+
}
|
301 |
+
@override
|
302 |
+
widget build(BuildContext context) {
|
303 |
+
return scaffold(
|
304 |
+
appBar: AppBar(
|
305 |
+
title: text(widget.title),
|
306 |
+
),
|
307 |
+
body: center(
|
308 |
+
child: FadeTransition(
|
309 |
+
opacity: curve,
|
310 |
+
child: const FlutterLogo(
|
311 |
+
size: 100,
|
312 |
+
),
|
313 |
+
),
|
314 |
+
),
|
315 |
+
floatingActionButton: FloatingActionButton(
|
316 |
+
tooltip: 'fade',
|
317 |
+
onPressed: () {
|
318 |
+
controller.forward();
|
319 |
+
},
|
320 |
+
child: const Icon(Icons.brush),
|
321 |
+
),
|
322 |
+
);
|
323 |
+
}
|
324 |
+
}
|
325 |
+
<code_end>
|
326 |
+
for more information, see
|
327 |
+
animation & motion widgets,
|
328 |
+
the animations tutorial,
|
329 |
+
and the animations overview.
|
330 |
+
<topic_end>
|
331 |
+
<topic_start>
|
332 |
+
how do i use a canvas to draw/paint?
|
333 |
+
in android, you would use the canvas and drawable
|
334 |
+
to draw images and shapes to the screen.
|
335 |
+
flutter has a similar canvas API as well,
|
336 |
+
since it’s based on the same low-level rendering engine, skia.
|
337 |
+
as a result, painting to a canvas in flutter
|
338 |
+
is a very familiar task for android developers.
|
339 |
+
flutter has two classes that help you draw to the canvas: CustomPaint
|
340 |
+
and CustomPainter,
|
341 |
+
the latter of which implements your algorithm to draw to the canvas.
|
342 |
+
to learn how to implement a signature painter in flutter,
|
343 |
+
see collin’s answer on custom paint.
|
344 |
+
<code_start>
|
345 |
+
import 'package:flutter/material.dart';
|
346 |
+
void main() => runApp(const MaterialApp(home: DemoApp()));
|
347 |
+
class DemoApp extends StatelessWidget {
|
348 |
+
const DemoApp({super.key});
|
349 |
+
@override
|
350 |
+
widget build(BuildContext context) => const scaffold(body: signature());
|
351 |
+
}
|
352 |
+
class signature extends StatefulWidget {
|
353 |
+
const signature({super.key});
|
354 |
+
@override
|
355 |
+
SignatureState createState() => SignatureState();
|
356 |
+
}
|
357 |
+
class SignatureState extends State<Signature> {
|
358 |
+
List<Offset?> _points = <offset>[];
|
359 |
+
@override
|
360 |
+
widget build(BuildContext context) {
|
361 |
+
return GestureDetector(
|
362 |
+
onPanUpdate: (details) {
|
363 |
+
setState(() {
|
364 |
+
RenderBox? referenceBox = context.findRenderObject() as RenderBox;
|
365 |
+
offset localPosition =
|
366 |
+
referenceBox.globalToLocal(details.globalPosition);
|
367 |
+
_points = List.from(_points)..add(localPosition);
|
368 |
+
});
|
369 |
+
},
|
370 |
+
onPanEnd: (details) => _points.add(null),
|
371 |
+
child: CustomPaint(
|
372 |
+
painter: SignaturePainter(_points),
|
373 |
+
size: size.infinite,
|
374 |
+
),
|
375 |
+
);
|
376 |
+
}
|
377 |
+
}
|
378 |
+
class SignaturePainter extends CustomPainter {
|
379 |
+
SignaturePainter(this.points);
|
380 |
+
final List<Offset?> points;
|
381 |
+
@override
|
382 |
+
void paint(Canvas canvas, size size) {
|
383 |
+
var paint = paint()
|
384 |
+
..color = colors.black
|
385 |
+
..strokeCap = StrokeCap.round
|
386 |
+
..strokeWidth = 5;
|
387 |
+
for (int i = 0; i < points.length - 1; i++) {
|
388 |
+
if (points[i] != null && points[i + 1] != null) {
|
389 |
+
canvas.drawLine(points[i]!, points[i + 1]!, paint);
|
390 |
+
}
|
391 |
+
}
|
392 |
+
}
|
393 |
+
@override
|
394 |
+
bool shouldRepaint(SignaturePainter oldDelegate) =>
|
395 |
+
oldDelegate.points != points;
|
396 |
+
}
|
397 |
+
<code_end>
|
398 |
+
<topic_end>
|
399 |
+
<topic_start>
|
400 |
+
how do i build custom widgets?
|
401 |
+
in android, you typically subclass view, or use a pre-existing view,
|
402 |
+
to override and implement methods that achieve the desired behavior.
|
403 |
+
in flutter, build a custom widget by composing
|
404 |
+
smaller widgets (instead of extending them).
|
405 |
+
it is somewhat similar to implementing a custom ViewGroup
|
406 |
+
in android, where all the building blocks are already existing,
|
407 |
+
but you provide a different behavior—for example,
|
408 |
+
custom layout logic.
|
409 |
+
for example, how do you build a CustomButton that takes a label in
|
410 |
+
the constructor? create a CustomButton that composes a ElevatedButton with
|
411 |
+
a label, rather than by extending ElevatedButton:
|
412 |
+
<code_start>
|
413 |
+
class CustomButton extends StatelessWidget {
|
414 |
+
final string label;
|
415 |
+
const CustomButton(this.label, {super.key});
|
416 |
+
@override
|
417 |
+
widget build(BuildContext context) {
|
418 |
+
return ElevatedButton(
|
419 |
+
onPressed: () {},
|
420 |
+
child: text(label),
|
421 |
+
);
|
422 |
+
}
|
423 |
+
}
|
424 |
+
<code_end>
|
425 |
+
then use CustomButton, just as you’d use any other flutter widget:
|
426 |
+
<code_start>
|
427 |
+
@override
|
428 |
+
widget build(BuildContext context) {
|
429 |
+
return const center(
|
430 |
+
child: CustomButton('Hello'),
|
431 |
+
);
|
432 |
+
}
|
433 |
+
<code_end>
|
434 |
+
<topic_end>
|
435 |
+
<topic_start>
|
436 |
+
intents
|
437 |
+
<topic_end>
|
438 |
+
<topic_start>
|
439 |
+
what is the equivalent of an intent in flutter?
|
440 |
+
in android, there are two main use cases for intents: navigating between
|
441 |
+
activities, and communicating with components. flutter, on the other hand,
|
442 |
+
does not have the concept of intents, although you can still start intents
|
443 |
+
through native integrations (using a plugin).
|
444 |
+
flutter doesn’t really have a direct equivalent to activities and fragments;
|
445 |
+
rather, in flutter you navigate between screens, using a navigator and
|
446 |
+
routes, all within the same activity.
|
447 |
+
a route is an abstraction for a “screen” or “page” of an app, and a
|
448 |
+
navigator is a widget that manages routes. a route roughly maps to an
|
449 |
+
activity, but it does not carry the same meaning. a navigator can push
|
450 |
+
and pop routes to move from screen to screen. navigators work like a stack
|
451 |
+
on which you can push() new routes you want to navigate to, and from
|
452 |
+
which you can pop() routes when you want to “go back”.
|
453 |
+
in android, you declare your activities inside the app’s AndroidManifest.xml.
|
454 |
+
in flutter, you have a couple options to navigate between pages:
|
455 |
+
the following example builds a map.
|
456 |
+
<code_start>
|
457 |
+
void main() {
|
458 |
+
runApp(MaterialApp(
|
459 |
+
home: const MyAppHome(), // becomes the route named '/'.
|
460 |
+
routes: <string, WidgetBuilder>{
|
461 |
+
'/a': (context) => const MyPage(title: 'page a'),
|
462 |
+
'/b': (context) => const MyPage(title: 'page b'),
|
463 |
+
'/c': (context) => const MyPage(title: 'page c'),
|
464 |
+
},
|
465 |
+
));
|
466 |
+
}
|
467 |
+
<code_end>
|
468 |
+
navigate to a route by pushing its name to the navigator.
|
469 |
+
<code_start>
|
470 |
+
Navigator.of(context).pushNamed('/b');
|
471 |
+
<code_end>
|
472 |
+
the other popular use-case for intents is to call external components such
|
473 |
+
as a camera or file picker. for this, you would need to create a native platform
|
474 |
+
integration (or use an existing plugin).
|
475 |
+
to learn how to build a native platform integration,
|
476 |
+
see developing packages and plugins.
|
477 |
+
<topic_end>
|
478 |
+
<topic_start>
|
479 |
+
how do i handle incoming intents from external applications in flutter?
|
480 |
+
flutter can handle incoming intents from android by directly talking to the
|
481 |
+
android layer and requesting the data that was shared.
|
482 |
+
the following example registers a text share intent filter on the native
|
483 |
+
activity that runs our flutter code, so other apps can share text with
|
484 |
+
our flutter app.
|
485 |
+
the basic flow implies that we first handle the shared text data on the
|
486 |
+
android native side (in our activity), and then wait until flutter requests
|
487 |
+
for the data to provide it using a MethodChannel.
|
488 |
+
first, register the intent filter for all intents in AndroidManifest.xml:
|
489 |
+
then in MainActivity, handle the intent, extract the text that was
|
490 |
+
shared from the intent, and hold onto it. when flutter is ready to process,
|
491 |
+
it requests the data using a platform channel, and it’s sent
|
492 |
+
across from the native side:
|
493 |
+
finally, request the data from the flutter side
|
494 |
+
when the widget is rendered:
|
495 |
+
<code_start>
|
496 |
+
import 'package:flutter/material.dart';
|
497 |
+
import 'package:flutter/services.dart';
|
498 |
+
void main() {
|
499 |
+
runApp(const SampleApp());
|
500 |
+
}
|
501 |
+
class SampleApp extends StatelessWidget {
|
502 |
+
const SampleApp({super.key});
|
503 |
+
// this widget is the root of your application.
|
504 |
+
@override
|
505 |
+
widget build(BuildContext context) {
|
506 |
+
return MaterialApp(
|
507 |
+
title: 'sample shared app handler',
|
508 |
+
theme: ThemeData(
|
509 |
+
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
|
510 |
+
),
|
511 |
+
home: const SampleAppPage(),
|
512 |
+
);
|
513 |
+
}
|
514 |
+
}
|
515 |
+
class SampleAppPage extends StatefulWidget {
|
516 |
+
const SampleAppPage({super.key});
|
517 |
+
@override
|
518 |
+
State<SampleAppPage> createState() => _SampleAppPageState();
|
519 |
+
}
|
520 |
+
class _SampleAppPageState extends State<SampleAppPage> {
|
521 |
+
static const platform = MethodChannel('app.channel.shared.data');
|
522 |
+
string dataShared = 'no data';
|
523 |
+
@override
|
524 |
+
void initState() {
|
525 |
+
super.initState();
|
526 |
+
getSharedText();
|
527 |
+
}
|
528 |
+
@override
|
529 |
+
widget build(BuildContext context) {
|
530 |
+
return scaffold(body: center(child: Text(dataShared)));
|
531 |
+
}
|
532 |
+
future<void> getSharedText() async {
|
533 |
+
var sharedData = await platform.invokeMethod('getSharedText');
|
534 |
+
if (shareddata != null) {
|
535 |
+
setState(() {
|
536 |
+
dataShared = sharedData;
|
537 |
+
});
|
538 |
+
}
|
539 |
+
}
|
540 |
+
}
|
541 |
+
<code_end>
|
542 |
+
<topic_end>
|
543 |
+
<topic_start>
|
544 |
+
what is the equivalent of startActivityForResult()?
|
545 |
+
the navigator class handles routing in flutter and is used to get
|
546 |
+
a result back from a route that you have pushed on the stack.
|
547 |
+
this is done by awaiting on the future returned by push().
|
548 |
+
for example, to start a location route that lets the user select
|
549 |
+
their location, you could do the following:
|
550 |
+
<code_start>
|
551 |
+
object? coordinates = await Navigator.of(context).pushNamed('/location');
|
552 |
+
<code_end>
|
553 |
+
and then, inside your location route, once the user has selected their location
|
554 |
+
you can pop the stack with the result:
|
555 |
+
<code_start>
|
556 |
+
navigator.of(context).pop({'lat': 43.821757, 'long': -79.226392});
|
557 |
+
<code_end>
|
558 |
+
<topic_end>
|
559 |
+
<topic_start>
|
560 |
+
async UI
|
561 |
+
<topic_end>
|
562 |
+
<topic_start>
|
563 |
+
what is the equivalent of runOnUiThread() in flutter?
|
564 |
+
dart has a single-threaded execution model, with support for isolates
|
565 |
+
(a way to run dart code on another thread), an event loop, and
|
566 |
+
asynchronous programming. unless you spawn an isolate, your dart code
|
567 |
+
runs in the main UI thread and is driven by an event loop. flutter’s event
|
568 |
+
loop is equivalent to android’s main looper—that is, the looper that
|
569 |
+
is attached to the main thread.
|
570 |
+
dart’s single-threaded model doesn’t mean you need to run everything as a
|
571 |
+
blocking operation that causes the UI to freeze. unlike android, which
|
572 |
+
requires you to keep the main thread free at all times, in flutter,
|
573 |
+
use the asynchronous facilities that the dart language provides, such as
|
574 |
+
async/await, to perform asynchronous work. you might be familiar with
|
575 |
+
the async/await paradigm if you’ve used it in c#, javascript, or if you
|
576 |
+
have used kotlin’s coroutines.
|
577 |
+
for example, you can run network code without causing the UI to hang by
|
578 |
+
using async/await and letting dart do the heavy lifting:
|
579 |
+
<code_start>
|
580 |
+
future<void> loadData() async {
|
581 |
+
var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
|
582 |
+
http.Response response = await http.get(dataURL);
|
583 |
+
setState(() {
|
584 |
+
widgets = jsonDecode(response.body);
|
585 |
+
});
|
586 |
+
}
|
587 |
+
<code_end>
|
588 |
+
once the awaited network call is done, update the UI by calling setState(),
|
589 |
+
which triggers a rebuild of the widget subtree and updates the data.
|
590 |
+
the following example loads data asynchronously and displays it in a ListView:
|
591 |
+
<code_start>
|
592 |
+
import 'dart:convert';
|
593 |
+
import 'package:flutter/material.dart';
|
594 |
+
import 'package:http/http.dart' as http;
|
595 |
+
void main() {
|
596 |
+
runApp(const SampleApp());
|
597 |
+
}
|
598 |
+
class SampleApp extends StatelessWidget {
|
599 |
+
const SampleApp({super.key});
|
600 |
+
@override
|
601 |
+
widget build(BuildContext context) {
|
602 |
+
return MaterialApp(
|
603 |
+
title: 'sample app',
|
604 |
+
theme: ThemeData(
|
605 |
+
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
|
606 |
+
),
|
607 |
+
home: const SampleAppPage(),
|
608 |
+
);
|
609 |
+
}
|
610 |
+
}
|
611 |
+
class SampleAppPage extends StatefulWidget {
|
612 |
+
const SampleAppPage({super.key});
|
613 |
+
@override
|
614 |
+
State<SampleAppPage> createState() => _SampleAppPageState();
|
615 |
+
}
|
616 |
+
class _SampleAppPageState extends State<SampleAppPage> {
|
617 |
+
list widgets = [];
|
618 |
+
@override
|
619 |
+
void initState() {
|
620 |
+
super.initState();
|
621 |
+
loadData();
|
622 |
+
}
|
623 |
+
@override
|
624 |
+
widget build(BuildContext context) {
|
625 |
+
return scaffold(
|
626 |
+
appBar: AppBar(
|
627 |
+
title: const Text('Sample app'),
|
628 |
+
),
|
629 |
+
body: ListView.builder(
|
630 |
+
itemCount: widgets.length,
|
631 |
+
itemBuilder: (context, position) {
|
632 |
+
return getRow(position);
|
633 |
+
},
|
634 |
+
),
|
635 |
+
);
|
636 |
+
}
|
637 |
+
widget getRow(int i) {
|
638 |
+
return padding(
|
639 |
+
padding: const EdgeInsets.all(10),
|
640 |
+
child: Text("Row ${widgets[i]["title"]}"),
|
641 |
+
);
|
642 |
+
}
|
643 |
+
future<void> loadData() async {
|
644 |
+
var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
|
645 |
+
http.Response response = await http.get(dataURL);
|
646 |
+
setState(() {
|
647 |
+
widgets = jsonDecode(response.body);
|
648 |
+
});
|
649 |
+
}
|
650 |
+
}
|
651 |
+
<code_end>
|
652 |
+
refer to the next section for more information on doing work in the
|
653 |
+
background, and how flutter differs from android.
|
654 |
+
<topic_end>
|
655 |
+
<topic_start>
|
656 |
+
how do you move work to a background thread?
|
657 |
+
in android, when you want to access a network resource you would typically
|
658 |
+
move to a background thread and do the work, as to not block the main thread,
|
659 |
+
and avoid ANRs. for example, you might be using an AsyncTask, a LiveData,
|
660 |
+
an IntentService, a JobScheduler job, or an RxJava pipeline with a
|
661 |
+
scheduler that works on background threads.
|
662 |
+
since flutter is single threaded and runs an event loop (like node.js), you
|
663 |
+
don’t have to worry about thread management or spawning background threads. if
|
664 |
+
you’re doing I/O-bound work, such as disk access or a network call, then
|
665 |
+
you can safely use async/await and you’re all set. if, on the other
|
666 |
+
hand, you need to do computationally intensive work that keeps the CPU busy,
|
667 |
+
you want to move it to an isolate to avoid blocking the event loop, like
|
668 |
+
you would keep any sort of work out of the main thread in android.
|
669 |
+
for I/O-bound work, declare the function as an async function,
|
670 |
+
and await on long-running tasks inside the function:
|
671 |
+
<code_start>
|
672 |
+
future<void> loadData() async {
|
673 |
+
var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
|
674 |
+
http.Response response = await http.get(dataURL);
|
675 |
+
setState(() {
|
676 |
+
widgets = jsonDecode(response.body);
|
677 |
+
});
|
678 |
+
}
|
679 |
+
<code_end>
|
680 |
+
this is how you would typically do network or database calls, which are both
|
681 |
+
I/O operations.
|
682 |
+
on android, when you extend AsyncTask, you typically override 3 methods,
|
683 |
+
onPreExecute(), doInBackground() and onPostExecute(). there is no
|
684 |
+
equivalent in flutter, since you await on a long-running function, and
|
685 |
+
dart’s event loop takes care of the rest.
|
686 |
+
however, there are times when you might be processing a large amount of data and
|
687 |
+
your UI hangs. in flutter, use isolates to take advantage of
|
688 |
+
multiple CPU cores to do long-running or computationally intensive tasks.
|
689 |
+
isolates are separate execution threads that do not share any memory
|
690 |
+
with the main execution memory heap. this means you can’t access variables from
|
691 |
+
the main thread, or update your UI by calling setState().
|
692 |
+
unlike android threads,
|
693 |
+
isolates are true to their name, and cannot share memory
|
694 |
+
(in the form of static fields, for example).
|
695 |
+
the following example shows, in a simple isolate, how to share data back to
|
696 |
+
the main thread to update the UI.
|
697 |
+
<code_start>
|
698 |
+
future<void> loadData() async {
|
699 |
+
ReceivePort receivePort = ReceivePort();
|
700 |
+
await Isolate.spawn(dataLoader, receivePort.sendPort);
|
701 |
+
// the 'echo' isolate sends its SendPort as the first message.
|
702 |
+
SendPort sendPort = await receivePort.first;
|
703 |
+
list msg = await sendReceive(
|
704 |
+
sendPort,
|
705 |
+
'https://jsonplaceholder.typicode.com/posts',
|
706 |
+
);
|
707 |
+
setState(() {
|
708 |
+
widgets = msg;
|
709 |
+
});
|
710 |
+
}
|
711 |
+
// the entry point for the isolate.
|
712 |
+
static future<void> dataLoader(SendPort sendPort) async {
|
713 |
+
// open the ReceivePort for incoming messages.
|
714 |
+
ReceivePort port = ReceivePort();
|
715 |
+
// notify any other isolates what port this isolate listens to.
|
716 |
+
sendPort.send(port.sendPort);
|
717 |
+
await for (var msg in port) {
|
718 |
+
string data = msg[0];
|
719 |
+
SendPort replyTo = msg[1];
|
720 |
+
string dataURL = data;
|
721 |
+
http.Response response = await http.get(Uri.parse(dataURL));
|
722 |
+
// lots of JSON to parse
|
723 |
+
replyTo.send(jsonDecode(response.body));
|
724 |
+
}
|
725 |
+
}
|
726 |
+
future sendReceive(SendPort port, msg) {
|
727 |
+
ReceivePort response = ReceivePort();
|
728 |
+
port.send([msg, response.sendPort]);
|
729 |
+
return response.first;
|
730 |
+
}
|
731 |
+
<code_end>
|
732 |
+
here, dataLoader() is the isolate that runs in its own separate
|
733 |
+
execution thread. in the isolate you can perform more CPU intensive
|
734 |
+
processing (parsing a big JSON, for example),
|
735 |
+
or perform computationally intensive math,
|
736 |
+
such as encryption or signal processing.
|
737 |
+
you can run the full example below:
|
738 |
+
<code_start>
|
739 |
+
import 'dart:async';
|
740 |
+
import 'dart:convert';
|
741 |
+
import 'dart:isolate';
|
742 |
+
import 'package:flutter/material.dart';
|
743 |
+
import 'package:http/http.dart' as http;
|
744 |
+
void main() {
|
745 |
+
runApp(const SampleApp());
|
746 |
+
}
|
747 |
+
class SampleApp extends StatelessWidget {
|
748 |
+
const SampleApp({super.key});
|
749 |
+
@override
|
750 |
+
widget build(BuildContext context) {
|
751 |
+
return MaterialApp(
|
752 |
+
title: 'sample app',
|
753 |
+
theme: ThemeData(
|
754 |
+
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
|
755 |
+
),
|
756 |
+
home: const SampleAppPage(),
|
757 |
+
);
|
758 |
+
}
|
759 |
+
}
|
760 |
+
class SampleAppPage extends StatefulWidget {
|
761 |
+
const SampleAppPage({super.key});
|
762 |
+
@override
|
763 |
+
State<SampleAppPage> createState() => _SampleAppPageState();
|
764 |
+
}
|
765 |
+
class _SampleAppPageState extends State<SampleAppPage> {
|
766 |
+
list widgets = [];
|
767 |
+
@override
|
768 |
+
void initState() {
|
769 |
+
super.initState();
|
770 |
+
loadData();
|
771 |
+
}
|
772 |
+
widget getBody() {
|
773 |
+
bool showLoadingDialog = widgets.isEmpty;
|
774 |
+
if (showloadingdialog) {
|
775 |
+
return getProgressDialog();
|
776 |
+
} else {
|
777 |
+
return getListView();
|
778 |
+
}
|
779 |
+
}
|
780 |
+
widget getProgressDialog() {
|
781 |
+
return const center(child: CircularProgressIndicator());
|
782 |
+
}
|
783 |
+
@override
|
784 |
+
widget build(BuildContext context) {
|
785 |
+
return scaffold(
|
786 |
+
appBar: AppBar(
|
787 |
+
title: const Text('Sample app'),
|
788 |
+
),
|
789 |
+
body: getBody(),
|
790 |
+
);
|
791 |
+
}
|
792 |
+
ListView getListView() {
|
793 |
+
return ListView.builder(
|
794 |
+
itemCount: widgets.length,
|
795 |
+
itemBuilder: (context, position) {
|
796 |
+
return getRow(position);
|
797 |
+
},
|
798 |
+
);
|
799 |
+
}
|
800 |
+
widget getRow(int i) {
|
801 |
+
return padding(
|
802 |
+
padding: const EdgeInsets.all(10),
|
803 |
+
child: Text("Row ${widgets[i]["title"]}"),
|
804 |
+
);
|
805 |
+
}
|
806 |
+
future<void> loadData() async {
|
807 |
+
ReceivePort receivePort = ReceivePort();
|
808 |
+
await Isolate.spawn(dataLoader, receivePort.sendPort);
|
809 |
+
// the 'echo' isolate sends its SendPort as the first message.
|
810 |
+
SendPort sendPort = await receivePort.first;
|
811 |
+
list msg = await sendReceive(
|
812 |
+
sendPort,
|
813 |
+
'https://jsonplaceholder.typicode.com/posts',
|
814 |
+
);
|
815 |
+
setState(() {
|
816 |
+
widgets = msg;
|
817 |
+
});
|
818 |
+
}
|
819 |
+
// the entry point for the isolate.
|
820 |
+
static future<void> dataLoader(SendPort sendPort) async {
|
821 |
+
// open the ReceivePort for incoming messages.
|
822 |
+
ReceivePort port = ReceivePort();
|
823 |
+
// notify any other isolates what port this isolate listens to.
|
824 |
+
sendPort.send(port.sendPort);
|
825 |
+
await for (var msg in port) {
|
826 |
+
string data = msg[0];
|
827 |
+
SendPort replyTo = msg[1];
|
828 |
+
string dataURL = data;
|
829 |
+
http.Response response = await http.get(Uri.parse(dataURL));
|
830 |
+
// lots of JSON to parse
|
831 |
+
replyTo.send(jsonDecode(response.body));
|
832 |
+
}
|
833 |
+
}
|
834 |
+
future sendReceive(SendPort port, msg) {
|
835 |
+
ReceivePort response = ReceivePort();
|
836 |
+
port.send([msg, response.sendPort]);
|
837 |
+
return response.first;
|
838 |
+
}
|
839 |
+
}
|
840 |
+
<code_end>
|
841 |
+
<topic_end>
|
842 |
+
<topic_start>
|
843 |
+
what is the equivalent of OkHttp on flutter?
|
844 |
+
making a network call in flutter is easy when you use the
|
845 |
+
popular http package.
|
846 |
+
while the http package doesn’t have every feature found in OkHttp,
|
847 |
+
it abstracts away much of the networking that you would normally implement
|
848 |
+
yourself, making it a simple way to make network calls.
|
849 |
+
to add the http package as a dependency, run flutter pub add:
|
850 |
+
to make a network call, call await on the async function http.get():
|
851 |
+
<code_start>
|
852 |
+
import 'dart:developer' as developer;
|
853 |
+
import 'package:http/http.dart' as http;
|
854 |
+
future<void> loadData() async {
|
855 |
+
var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
|
856 |
+
http.Response response = await http.get(dataURL);
|
857 |
+
developer.log(response.body);
|
858 |
+
}
|
859 |
+
<code_end>
|
860 |
+
<topic_end>
|
861 |
+
<topic_start>
|
862 |
+
how do i show the progress for a long-running task?
|
863 |
+
in android you would typically show a ProgressBar view in your UI while
|
864 |
+
executing a long-running task on a background thread.
|
865 |
+
in flutter, use a ProgressIndicator widget.
|
866 |
+
show the progress programmatically by controlling when it’s rendered
|
867 |
+
through a boolean flag. tell flutter to update its state before your
|
868 |
+
long-running task starts, and hide it after it ends.
|
869 |
+
in the following example, the build function is separated into three different
|
870 |
+
functions. if showLoadingDialog is true (when widgets.isEmpty),
|
871 |
+
then render the ProgressIndicator. otherwise, render the
|
872 |
+
ListView with the data returned from a network call.
|
873 |
+
<code_start>
|
874 |
+
import 'dart:convert';
|
875 |
+
import 'package:flutter/material.dart';
|
876 |
+
import 'package:http/http.dart' as http;
|
877 |
+
void main() {
|
878 |
+
runApp(const SampleApp());
|
879 |
+
}
|
880 |
+
class SampleApp extends StatelessWidget {
|
881 |
+
const SampleApp({super.key});
|
882 |
+
@override
|
883 |
+
widget build(BuildContext context) {
|
884 |
+
return MaterialApp(
|
885 |
+
title: 'sample app',
|
886 |
+
theme: ThemeData(
|
887 |
+
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
|
888 |
+
),
|
889 |
+
home: const SampleAppPage(),
|
890 |
+
);
|
891 |
+
}
|
892 |
+
}
|
893 |
+
class SampleAppPage extends StatefulWidget {
|
894 |
+
const SampleAppPage({super.key});
|
895 |
+
@override
|
896 |
+
State<SampleAppPage> createState() => _SampleAppPageState();
|
897 |
+
}
|
898 |
+
class _SampleAppPageState extends State<SampleAppPage> {
|
899 |
+
list widgets = [];
|
900 |
+
@override
|
901 |
+
void initState() {
|
902 |
+
super.initState();
|
903 |
+
loadData();
|
904 |
+
}
|
905 |
+
widget getBody() {
|
906 |
+
bool showLoadingDialog = widgets.isEmpty;
|
907 |
+
if (showloadingdialog) {
|
908 |
+
return getProgressDialog();
|
909 |
+
} else {
|
910 |
+
return getListView();
|
911 |
+
}
|
912 |
+
}
|
913 |
+
widget getProgressDialog() {
|
914 |
+
return const center(child: CircularProgressIndicator());
|
915 |
+
}
|
916 |
+
@override
|
917 |
+
widget build(BuildContext context) {
|
918 |
+
return scaffold(
|
919 |
+
appBar: AppBar(
|
920 |
+
title: const Text('Sample app'),
|
921 |
+
),
|
922 |
+
body: getBody(),
|
923 |
+
);
|
924 |
+
}
|
925 |
+
ListView getListView() {
|
926 |
+
return ListView.builder(
|
927 |
+
itemCount: widgets.length,
|
928 |
+
itemBuilder: (context, position) {
|
929 |
+
return getRow(position);
|
930 |
+
},
|
931 |
+
);
|
932 |
+
}
|
933 |
+
widget getRow(int i) {
|
934 |
+
return padding(
|
935 |
+
padding: const EdgeInsets.all(10),
|
936 |
+
child: Text("Row ${widgets[i]["title"]}"),
|
937 |
+
);
|
938 |
+
}
|
939 |
+
future<void> loadData() async {
|
940 |
+
var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
|
941 |
+
http.Response response = await http.get(dataURL);
|
942 |
+
setState(() {
|
943 |
+
widgets = jsonDecode(response.body);
|
944 |
+
});
|
945 |
+
}
|
946 |
+
}
|
947 |
+
<code_end>
|
948 |
+
<topic_end>
|