Dart
199 bites tagged Dart — interview questions with model answers, and 60-second explainers.
How would you draw a line graph using Canvas and Path?
Use moveTo for the first point, lineTo for the rest, then Canvas.drawPath with a stroke Paint. Fluency with Flutter's imperative drawing model and Path construction.
How do you safely add a non-nullable column in sqflite?
Tests onCreate for fresh installs vs onUpgrade for existing data. Outline: bump version; in onUpgrade use ALTER TABLE ADD COLUMN NOT NULL DEFAULT for existing rows; keep onCreate as latest schema. Red flag: only changing onCreate so old users crash.
Why is Flutter local storage async and how do you use shared_preferences?
Tests why disk I/O must avoid blocking Dart's UI thread. A strong answer shows async/await with getInstance and setters, notes legacy getters are sync-after-cache, and warns writes may not persist instantly.
Why are stale search requests problematic and how do you cancel them?
This tests race conditions and resource waste in async UI. Strong answers note stale requests waste bandwidth and overwrite newer results; cancel the previous call with a CancelToken before issuing the next.
Explain Dio interceptors and automatic token refresh
Define interceptors as hooks; queue concurrent 401s during refresh; retry with Bearer header via token manager. Stateful middleware and async orchestration. Synchronous refresh or refresh storms.
Compare manual JSON serialization versus json_serializable
It tests build automation versus manual control in Dart serialization. Manual methods avoid build steps but risk drift; code generation cuts boilerplate but adds compile latency. Claiming code gen slows runtime or that manual is always simpler.
Describe a robust error handling strategy for network requests
Tests whether you classify failures by layer rather than catching everything generically. Inspect DioExceptionType for connectivity, check HTTP status before parsing, and isolate JSON decode errors. Never show the same message for timeouts and 500s.
Purpose of factory fromJson constructor in Dart models
Factory fromJson centralizes deserialization, preprocesses Map values before instantiation, and keeps the primary constructor clean. Why factory constructors separate parsing from creation.
Explain FutureBuilder and how it manages async UI states
This tests declarative async UI state management. Obtain the Future before build, pass it to FutureBuilder, and branch on snapshot.connectionState and hasError to render loading, data, or error states.
Make a GET request with http and parse JSON in Dart
Practical Dart async networking with package:http and dart:convert. Import http, await get(Uri.parse(url)), verify statusCode is 200, then jsonDecode(response.body) as List<Map<String, dynamic>>. Skipping status checks or decoding without a cast.
Implement a GoRouter path parameter route and access userId in a widget
This tests GoRouter declarative routing and GoRouterState. Define a GoRoute with path '/users/:userId', read state.params['userId'] in the builder, and handle null-safety. A red flag is parsing the URI manually or using ModalRoute.of instead of state.params.
How do you pass data with Navigator.push and return data with Navigator.pop?
Tests imperative navigation and async result patterns. Strong answer: push via MaterialPageRoute with constructor args; await the Future from Navigator.push; pop with Navigator.pop(context, result). Red flag: using global state instead of the Future result.
What is a FocusNode and why is it useful in forms?
This tests your understanding of Flutter's imperative focus tree. A strong answer defines FocusNode as a persistent focus target, explains programmatic form navigation, and stresses initState creation and dispose.
Explain the validator property in TextFormField and what triggers error display
Tests Form validation lifecycle knowledge. Strong answer: validator returns String? error or null; formKey.currentState.validate() triggers all fields; returned string renders as inline error.
How do you retrieve and listen to TextField changes in Flutter?
Use TextEditingController, attach to TextField, listen with addListener, read controller.text, dispose in State.dispose. Flutter input state and lifecycle hygiene. Citing onChanged as standard or forgetting disposal.
What problem does IntrinsicWidth solve and what are its performance costs?
This tests Flutter constraints and intrinsic sizing. A great answer covers: capping width to the child's max intrinsic width, aligning Column children, and the speculative pass that costs O(N²) in tree depth. A red flag is omitting performance cost.
Fix RenderFlex overflow in Row with long truncating text
Wrap Text in Expanded; set overflow to TextOverflow.ellipsis and maxLines: 1; leave siblings unwrapped. Flutter Row constraints and bounding Text width for ellipsis without affecting sibling sizes.
How do Flexible and Expanded differ in a Row or Column?
Tests Flutter main-axis flex constraints. Key point: Flexible uses FlexFit.loose so the child may be smaller than its space share; Expanded uses FlexFit.tight so the child must fill its share.
How do you split a Column 1/3 and 2/3 using Expanded?
Tests understanding of flex allocation in Flutter layouts. Strong answers wrap both containers in Expanded, assign flex values of 1 and 2, and note that Expanded forces children to fill the Column's main axis. Red flag: proposing fixed heights instead of flex.
How does const on a widget constructor impact build and reconciliation?
Tests widget canonicalization and reconciliation. Strong answers: const creates identical widget instances; Element.updateChild skips subtree rebuild when oldWidget == newWidget, saving elements and GC.
What is BuildContext? Give two tree-interaction examples.
Tests if you know BuildContext is an Element handle to a widget's tree location. Strong answers cite Theme.of and Scaffold.of as ancestor lookups, explain the own-context trap, and warn against caching across async gaps. Red flag: calling it the widget itself.
Explain StatelessWidget vs StatefulWidget and when to choose each
This tests immutable UI versus persistent state. StatelessWidget rebuilds when config changes; StatefulWidget owns State surviving rebuilds. Use StatelessWidget for static UI and StatefulWidget for interactive elements.
Explain StreamController, write a broadcast stream example, and why close it?
This tests Dart stream lifecycle and memory safety. A strong answer uses StreamController.broadcast(), adds data and errors, closes it, and explains unclosed controllers leak memory.
Fetch user profiles concurrently and handle individual failures
Tests Future.wait concurrency and per-future error isolation. Answer: map IDs to fetchProfile, pass to Future.wait. For partial failures, attach catchError per future to return null, then filter. Red flag: try-catch around Future.wait or sequential awaits.
Get Dart bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.