Posts

Showing posts from October, 2025

What is the role of main.dart?

  main.dart is the entry point of every Flutter app. It contains main() and usually starts with: void main() { runApp(MyApp()); }

How to use SharedPreferences in Flutter?

 final prefs = await SharedPreferences.getInstance(); await prefs.setString('username', 'Ankur'); print(prefs.getString('username'));

How to show a Snackbar in Flutter?

 ScaffoldMessenger.of(context).showSnackBar(   SnackBar(content: Text("Saved successfully!")), );

What is GestureDetector in Flutter?

  GestureDetector detects touch interactions (tap, double-tap, swipe, etc.) Example: GestureDetector( onTap: () { print("Tapped!"); }, child: Container( color: Colors.blue, child: Text("Tap Me"), ), );

What are constraints in Flutter Layout?

 Each widget in Flutter receives constraints from its parent (min and max width/height). The widget must fit inside those constraints. Example: Container( constraints: BoxConstraints(maxWidth: 200), child: Text("Hello World"), );

What is FutureBuilder and StreamBuilder?

 Both are widgets to handle asynchronous data. FutureBuilder – For one-time data (Future) FutureBuilder( future: getData(), builder: (context, snapshot) { if (snapshot.hasData) return Text(snapshot.data); return CircularProgressIndicator(); }, ); StreamBuilder – For continuous data (Stream) StreamBuilder( stream: counterStream, builder: (context, snapshot) { if (snapshot.hasData) return Text('${snapshot.data}'); return CircularProgressIndicator(); }, );

What is ListView and its types?

  ListView is used for displaying a scrollable list of items. Types: ListView() – Default constructor ListView.builder() – Efficient for long lists ListView.separated() – With separators ListView.custom() – Custom behavior Example: ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return ListTile(title: Text(items[index])); }, );

What are GlobalKeys and when to use them?

  GlobalKey uniquely identifies widgets across the widget tree — useful to: Access widget state from anywhere Validate a form Scroll to a widget Example: final formKey = GlobalKey<FormState>(); Form( key: formKey, child: TextFormField(), );

What is BuildContext used for?

  It provides information about the location of a widget in the widget tree. Used to: Access Theme.of(context) Navigate ( Navigator.of(context) ) Show dialogs/snackbars

What is the purpose of async and yield in Dart?*

 Used to create Streams easily. Example: Stream<int> numbers() async* { for (int i = 1; i <= 5; i++) { yield i; // emits value } }

What is the difference between final, const, and var in Dart?

  Keyword Description Example var Variable with dynamic type var name = "Ankur"; final Value cannot be reassigned final age = 30; const Compile-time constant const pi = 3.14;

What are Mixins in Flutter (Dart)?

 Mixins are a way to reuse code in multiple classes without inheritance. Example: mixin Logger { void log(String message) => print(message); } class MyApp with Logger { void run() { log("App started"); } }

What is the difference between Expanded and Flexible?

  Widget Behavior Expanded Takes all available space Flexible Takes only the needed space Example: Row( children: [ Expanded(child: Container(color: Colors.red)), Flexible(child: Container(color: Colors.blue)), ], );

What is Flutter Layout System?

  Flutter uses a constraint-based layout system . Each widget tells its parent how big it wants to be, and the parent gives constraints in return. Common Layout Widgets: Container Row Column Expanded Flexible Stack Wrap

How do you handle API calls in Flutter?

 Use the http or dio package. Example using http : final response = await http.get(Uri.parse('https://api.example.com/data')); if (response.statusCode == 200) { var data = jsonDecode(response.body); } Example using Dio (with headers): Dio dio = Dio(); Response response = await dio.post( 'https://api.example.com/upload', data: {'name': 'Ankur'}, options: Options(headers: {'Authorization': 'Bearer token'}), );

What is Navigator 2.0 in Flutter?

 Navigator 2.0 (Router API) provides declarative navigation — useful for web and large apps. Instead of pushing/popping pages imperatively, you manage the full stack of pages as a list. Example: MaterialApp.router( routerDelegate: MyRouterDelegate(), routeInformationParser: MyRouteParser(), );

What is the difference between Future, Stream, and async/await?

  Type Description Example Future Single value returned in future Future<int> getData() Stream Sequence of values over time Stream<int> getNumbers() async/await Used to handle Futures easily await getData() Example: Stream<int> counter() async* { for (int i = 0; i < 5; i++) { await Future.delayed(Duration(seconds: 1)); yield i; } }

What is BLoC in Flutter?

  BLoC (Business Logic Component) separates the UI from business logic using Streams . Input: Events (via Sink ) Output: States (via Stream ) Example: class CounterBloc { final _countController = StreamController<int>(); int _count = 0; Stream<int> get countStream => _countController.stream; void increment() { _count++; _countController.sink.add(_count); } void dispose() { _countController.close(); } } Advantages: Clean architecture Reusable and testable code

What is Provider in Flutter?

  Provider is a wrapper around InheritedWidget that helps manage and share app state efficiently. Example: class Counter with ChangeNotifier { int count = 0; void increment() { count++; notifyListeners(); // UI refreshes } } In main: ChangeNotifierProvider( create: (_) => Counter(), child: MyApp(), ); Use in UI: Consumer<Counter>( builder: (context, counter, child) => Text('${counter.count}'), );

What is State Management in Flutter?

  State management means managing data and UI updates in your app. When the app data (state) changes, the UI should rebuild to reflect that change. Popular State Management Approaches: setState() – Simple and built-in Provider – Officially recommended by Google GetX – Lightweight, reactive, and simple BLoC / Cubit – Business logic component, uses streams MobX – Reactive state management Riverpod – Improved version of Provider

What is the use of Keys in Flutter?

 Keys help Flutter identify widgets uniquely — useful when widgets move or get rebuilt. Example: TextField(key: ValueKey('username'));

What is the Lifecycle of a StatefulWidget?

  createState() initState() build() didUpdateWidget() setState() deactivate() dispose()

What is Theme in Flutter?

 Used to define the colors, fonts, and overall look of the app. Example: MaterialApp( theme: ThemeData( primarySwatch: Colors.blue, textTheme: TextTheme(bodyMedium: TextStyle(fontSize: 18)), ), );

What is InheritedWidget?

  InheritedWidget is a base class for widgets that pass data down the widget tree efficiently. Used by state management solutions like Provider .

What is the difference between runApp() and main()?

  main() is the entry point of the Dart program. runApp() inflates the given widget and attaches it to the screen. Example: void main() { runApp(MyApp()); }

What is async and await in Flutter?

 They are used for asynchronous operations (non-blocking code). Example: void fetchData() async { var response = await http.get(Uri.parse('https://api.example.com')); print(response.body); }

What is a Future in Flutter?

  Future represents an asynchronous computation that will complete later. Example: Future<String> getData() async { return "Hello World"; } Use with await : String data = await getData();

What is Scaffold in Flutter?

  Scaffold provides a basic material design layout for the app. It includes: AppBar Drawer BottomNavigationBar FloatingActionButton Body Example: Scaffold( appBar: AppBar(title: Text("Home")), body: Center(child: Text("Hello")), floatingActionButton: FloatingActionButton(onPressed: () {}), );

What is the difference between MainAxisAlignment and CrossAxisAlignment?

  Used in Row and Column to align children. Property Row Column mainAxisAlignment Horizontal alignment Vertical alignment crossAxisAlignment Vertical alignment Horizontal alignment Example: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Hello'), Text('World')], );

What is setState() in Flutter?

 Used in StatefulWidget to update the UI when data changes. Example: setState(() { count++; }); This tells Flutter to rebuild the widget with the updated data.

What are Packages and Plugins in Flutter?

  Package: Reusable Dart code (e.g., http , provider ) Plugin: Package that also includes platform-specific code (e.g., camera , shared_preferences ) Install using: flutter pub add http Import and use: import 'package:http/http.dart' as http;

How do you navigate between screens in Flutter?

 Using Navigator class: Navigator.push( context, MaterialPageRoute(builder: (context) => SecondScreen()), ); To go back: Navigator.pop(context); Or using named routes : Navigator.pushNamed(context, '/second');

What is a BuildContext?

  BuildContext is a handle to the location of a widget in the widget tree. It helps Flutter know where a widget is located and what its parent/child relationships are . Example: Widget build(BuildContext context) { return Text('Hello'); } You use context to access theme, navigation, or inherited widgets.

What is pubspec.yaml file?

 It’s the configuration file for a Flutter project. It includes: App name, version, description Dependencies (packages, plugins) Assets (images, fonts) Environment SDK version Example: name: my_app dependencies: flutter: sdk: flutter http: ^1.2.0 assets: - images/logo.png

What is Hot Reload and Hot Restart?

  Feature Hot Reload Hot Restart Description Updates code changes instantly without restarting the app Restarts the app and rebuilds widget tree Keeps State? Yes No Use Case UI changes Logic changes affecting state initialization

What is the Widget Tree?

  Every Flutter app is a tree of widgets . Each widget nests inside another to create the complete UI structure. Example: MaterialApp( home: Scaffold( appBar: AppBar(title: Text("Hello")), body: Center(child: Text("Welcome")), ), ); Here, the tree looks like: MaterialApp → Scaffold → AppBar → Text / Center → Text

Difference between StatelessWidget and StatefulWidget

  Feature StatelessWidget StatefulWidget Definition Can’t change once built Can change at runtime State No internal state Has a mutable state Use case Static UI Dynamic UI Example Text, Icon Form, Switch, Checkbox

What is a Widget in Flutter?

 Everything in Flutter is a widget — text, button, padding, layout, etc. Widgets are building blocks of the Flutter UI. Types of Widgets: StatelessWidget: Immutable — once built, it doesn’t change. Example: Text , Icon , RaisedButton . StatefulWidget: Mutable — can change during runtime. Example: Checkbox , TextField , Slider .

What is Dart?

 Dart is the programming language used by Flutter. It’s object-oriented, class-based , and compiled ahead-of-time (AOT) into native code for performance. Features of Dart: Sound null safety Asynchronous programming with async and await Strong typing Just-in-time (JIT) for development & AOT for production

1. What is Flutter?

 Flutter is an open-source UI toolkit developed by Google for building natively compiled applications for mobile (Android, iOS), web, desktop , and embedded devices from a single codebase . Language used: Dart Rendering Engine: Skia Developed by: Google       Advantages: Single codebase for multiple platforms Hot reload for faster development High performance (compiles to native ARM code) Rich widget library