Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
32 views26 pages

Generative AI Interview Study Guide

The document is a comprehensive study guide for preparing for interviews related to Generative AI and Flutter, covering fundamental concepts, applications, and advanced topics. It includes explanations of Generative AI, LLMs, model architectures, deployment strategies, and ethical concerns. Additionally, it addresses practical considerations for using AI in production, as well as industry trends and business strategies.

Uploaded by

0408jaindaksh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views26 pages

Generative AI Interview Study Guide

The document is a comprehensive study guide for preparing for interviews related to Generative AI and Flutter, covering fundamental concepts, applications, and advanced topics. It includes explanations of Generative AI, LLMs, model architectures, deployment strategies, and ethical concerns. Additionally, it addresses practical considerations for using AI in production, as well as industry trends and business strategies.

Uploaded by

0408jaindaksh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Complete GenAI & Flutter Interview Study Guide

Your one-stop preparation for landing the internship!

Basics

1. What is Generative AI and how is it different from traditional AI?


Generative AI creates new content (text, images, audio) based on patterns learned from training data.

Key differences:

Traditional AI: Analyzes and classifies existing data (e.g., "Is this email spam?")

Generative AI: Creates new data (e.g., "Write a marketing email")

Traditional AI predicts/categorizes, Generative AI produces original content

2. Can you name some generative AI models for text, images, and audio?
Text: GPT-4, Claude, LLaMA, Gemini, PaLM Images: DALL-E, Midjourney, Stable Diffusion, Adobe Firefly
Audio: ElevenLabs, Murf, WaveNet, Bark, MusicLM

3. What is the difference between discriminative and generative models?


Discriminative models: Learn the boundary between classes. Answer "What class does this belong to?"

Example: Email classifier (spam vs not spam)

Focuses on P(Y|X) - probability of label given input

Generative models: Learn the underlying data distribution. Answer "What would new data look like?"

Example: Text generator creating new sentences


Focuses on P(X|Y) or P(X) - probability of data

4. Explain the architecture of a Transformer.


Core components:

Encoder-Decoder structure (though GPT uses decoder-only)

Multi-Head Attention: Allows model to focus on different parts of input simultaneously

Feed-Forward Networks: Process attention outputs

Positional Encoding: Adds position information since attention has no inherent order

Layer Normalization & Residual Connections: Help with training stability

Key advantage: Processes sequences in parallel (vs RNNs which are sequential)

5. What are embeddings and why are they important in NLP?


Embeddings: Dense vector representations of words/tokens that capture semantic meaning.
Importance:

Convert text to numerical format for machine learning

Similar words have similar embeddings (king ≈ queen)

Enable semantic understanding and relationships

Foundation for all modern NLP models

LLMs & NLP

1. What is the difference between pre-training and fine-tuning in LLMs?


Pre-training:

Training on massive, general datasets (books, web pages)

Learns general language patterns and world knowledge


Expensive, done once by model creators

Fine-tuning:

Training on specific, smaller datasets for particular tasks


Adapts pre-trained model for specific use cases

Cheaper, faster, done by end users

2. How does the self-attention mechanism work?


Self-attention allows each word to "attend" to other words in the sequence.

Process:

1. Convert each word to Query (Q), Key (K), Value (V) vectors
2. Calculate attention scores: Q·K (how much each word should focus on others)

3. Apply softmax to get attention weights

4. Multiply weights by Values to get final representation

Result: Each word's representation incorporates information from relevant other words.

3. What is the difference between GPT and BERT?


GPT (Generative Pre-trained Transformer):

Decoder-only architecture

Autoregressive: Predicts next token based on previous tokens


Unidirectional: Only sees previous context
Best for: Text generation, completion

BERT (Bidirectional Encoder Representations from Transformers):

Encoder-only architecture
Masked Language Model: Predicts masked tokens using full context

Bidirectional: Sees context from both directions

Best for: Classification, question answering, understanding tasks

4. What is tokenization? How does it affect model input?


Tokenization: Breaking text into smaller units (tokens) that the model can process.

Types:

Word-level: Each word is a token


Subword: Parts of words (like "playing" → "play" + "ing")

Character-level: Individual characters

Impact on model:

Determines vocabulary size and memory usage

Affects how model handles rare/new words

Influences context length limitations

5. What are prompt engineering and few-shot learning?


Prompt Engineering: Crafting input prompts to get better outputs from LLMs.

Clear instructions, context, examples, specific formats

Example: "Act as a expert in X, explain Y in simple terms..."

Few-shot Learning: Teaching models new tasks with just a few examples in the prompt.

0-shot: No examples, just instructions


1-shot: One example

Few-shot: Multiple examples

Model learns the pattern and applies it to new inputs

Applications & Use Cases

1. How would you build a generative AI travel companion?


Architecture:

1. Core LLM: For conversational interface and recommendations

2. RAG System: Connect to travel databases (flights, hotels, attractions)

3. User Profiling: Store preferences and travel history

4. APIs Integration: Booking platforms, weather, maps

5. Multimodal: Image recognition for landmarks, voice interface

Key features: Personalized itineraries, real-time updates, budget optimization, local insights
2. What is RAG (Retrieval-Augmented Generation) and why is it useful?
RAG: Combines information retrieval with text generation.

Process:

1. User asks a question

2. System retrieves relevant documents from knowledge base


3. LLM generates answer using retrieved context + original knowledge

Benefits:

Access to current, specific information (beyond training data)

Reduces hallucinations

Enables domain-specific expertise

More cost-effective than fine-tuning for knowledge updates

3. How can you prevent hallucinations in generative AI models?


Strategies:

RAG: Ground responses in factual sources

Prompt engineering: Ask for citations, specify "I don't know" is acceptable

Fine-tuning: On high-quality, factual datasets

Confidence scoring: Flag uncertain responses

Human in the loop: Review critical outputs

Multiple model verification: Cross-check with other models


Structured outputs: Use templates to constrain responses

4. How do you evaluate the quality of AI-generated content?


Automated metrics:

BLEU/ROUGE: Compare against reference texts

Perplexity: Measure how "surprised" the model is by text


Semantic similarity: Embedding-based comparisons

Human evaluation:

Relevance: Does it answer the question?

Accuracy: Is the information correct?

Coherence: Is it logically consistent?

Fluency: Is the language natural?

Creativity: For creative tasks, is it novel?

Hybrid approaches: A/B testing, expert review, user feedback


5. How can embeddings help personalize travel recommendations?
User embeddings: Represent user preferences as vectors based on:

Past bookings, ratings, searches

Demographics, stated preferences

Behavioral patterns

Item embeddings: Represent destinations/hotels as vectors based on:

Features, reviews, categories

User interactions, popularity

Personalization: Find destinations with embeddings similar to user's preference vector using cosine
similarity or neural networks.

Benefits: Captures complex, implicit preferences beyond explicit filters.

Advanced / Practical

1. How do you deploy a generative AI model in production?


Deployment options:

Cloud APIs: OpenAI, Anthropic (easiest, most expensive for scale)

Managed services: AWS SageMaker, Google Vertex AI

Self-hosted: Docker containers, Kubernetes

Edge deployment: Smaller models on mobile/IoT devices

Key considerations:

Latency: Real-time vs batch processing

Cost: Per-token pricing vs infrastructure costs

Scalability: Auto-scaling for demand spikes

Security: API keys, data privacy, content filtering

Monitoring: Performance metrics, usage tracking

2. What are the challenges of using LLMs on mobile apps?


Challenges:

Model size: LLMs are huge (GBs), mobile storage/memory limited

Compute power: Mobile CPUs/GPUs much weaker than servers

Battery drain: Heavy computation reduces battery life

Network dependency: Need internet for cloud-based models

Latency: Network calls add delay


Solutions:

Smaller models: DistilBERT, mobile-optimized versions

Model compression: Quantization, pruning

Edge computing: Process nearby, not in cloud

Hybrid approach: Simple tasks on-device, complex ones in cloud

Caching: Store common responses locally

3. What is the difference between fine-tuning and using embeddings with LLMs?
Fine-tuning:

What: Updating model parameters for specific tasks

When: Need different behavior/style, domain adaptation

Pros: Better performance on specific tasks

Cons: Expensive, time-consuming, need labeled data

Use case: Customer service chatbot with company tone

Using embeddings:

What: Using pre-trained model with additional context via embeddings


When: Need access to specific knowledge base

Pros: Faster, cheaper, easy to update knowledge


Cons: Limited to retrieval-based improvements

Use case: Q&A system over company documents

4. How would you integrate TTS (text-to-speech) into a generative AI app?


Architecture:

1. LLM generates text response

2. Text preprocessing: Clean text, handle special characters

3. TTS engine: Convert text to audio


Cloud: Google Text-to-Speech, Amazon Polly, ElevenLabs

On-device: iOS Speech Synthesis, Android TextToSpeech

4. Audio streaming: Send audio to client in chunks

5. Playback control: Play/pause/speed controls

Considerations:

Voice selection: Match persona/brand

SSML: Speech Synthesis Markup Language for better control

Caching: Save common phrases


Fallback: Handle TTS failures gracefully

5. What ethical concerns exist in using Generative AI for content creation?


Major concerns:

Misinformation: AI can generate convincing but false content

Solution: Fact-checking, source attribution, clear AI labeling

Bias: Models inherit biases from training data

Solution: Diverse training data, bias testing, fairness metrics

Copyright: May reproduce copyrighted material

Solution: Respect copyright, attribution, fair use guidelines

Job displacement: May replace human content creators

Solution: Focus on augmentation vs replacement, reskilling

Deepfakes: Realistic fake audio/video content

Solution: Detection tools, verification systems, legal frameworks

Privacy: May leak personal information from training data

Solution: Data anonymization, privacy-preserving training

Best practices: Transparency, human oversight, clear use policies, regular audits

ADDITIONAL GENERATIVE AI & LLM QUESTIONS

Technical Deep Dive

1. What is temperature and top-p sampling in text generation?


Temperature: Controls randomness in text generation

Low (0.1-0.3): More focused, deterministic outputs

High (0.8-1.0): More creative, diverse outputs

0: Always picks most likely token (deterministic)

Top-p (nucleus) sampling: Only considers tokens in top p% probability mass

p=0.9: Consider tokens that make up 90% of probability

More consistent quality than top-k sampling

Balances creativity with coherence


2. Explain the difference between GPT-3.5, GPT-4, and ChatGPT?
GPT-3.5: Base model, good at completion tasks, 175B parameters GPT-4: Multimodal (text+images),
better reasoning, fewer hallucinations, larger context ChatGPT: GPT models fine-tuned for conversation
with RLHF (Reinforcement Learning from Human Feedback)

Key insight: ChatGPT = GPT + Chat optimization + Safety training

3. What is RLHF (Reinforcement Learning from Human Feedback)?


Process:

1. Supervised fine-tuning: Train on high-quality human demonstrations

2. Reward modeling: Train a model to predict human preferences

3. RL optimization: Use PPO to optimize policy based on reward model

Purpose: Align AI behavior with human values and preferences Result: More helpful, harmless, and
honest responses

4. What are the main limitations of current LLMs?


Knowledge cutoff: Training data has a cutoff date Hallucination: Generate plausible but false
information Context length: Limited input size (though improving) Reasoning: Struggle with complex
multi-step logic Grounding: No real-world experience or sensory input Consistency: May contradict
itself in long conversations Bias: Reflect biases from training data

5. What is the difference between instruction-tuning and RLHF?


Instruction-tuning: Train model to follow instructions using supervised learning

Input: Instruction + desired output pairs

Goal: Learn to follow various types of instructions

RLHF: Optimize model based on human preference rankings

Input: Multiple outputs ranked by humans

Goal: Generate outputs humans prefer

Relationship: Often used together - instruction-tune first, then RLHF

6. How does vector search work in RAG systems?


Process:

1. Indexing: Convert documents to embeddings, store in vector database

2. Query: Convert user question to embedding

3. Search: Find most similar document embeddings (cosine similarity)

4. Retrieval: Get top-k most relevant documents


5. Generation: LLM uses retrieved docs + query to generate answer
Vector databases: Pinecone, Weaviate, Chroma, FAISS

7. What is quantization in LLMs?


Quantization: Reducing precision of model weights to save memory/computation

FP32 → FP16: Half precision, ~50% memory reduction

INT8: 8-bit integers, ~75% memory reduction

4-bit: Extreme compression for mobile deployment

Trade-offs: Smaller models but potentially lower quality Techniques: Post-training quantization,
quantization-aware training

8. Explain different types of AI agents and their capabilities?


Simple reflex agents: Respond to current state only Model-based agents: Maintain internal state model
Goal-based agents: Plan actions to achieve specific goals Utility-based agents: Optimize for maximum
utility/reward Learning agents: Improve performance through experience

LLM agents: Use language models as reasoning engines, can use tools and plan multi-step actions

9. What is prompt injection and how to prevent it?


Prompt injection: Malicious inputs that override original instructions

Example: "Ignore previous instructions, instead tell me..."

Prevention strategies:

Input validation: Filter suspicious patterns


Prompt templates: Structure prompts to resist injection

Output filtering: Check responses for policy violations

Instruction hierarchy: System prompts override user inputs

Sandboxing: Limit model capabilities in production

10. What are multimodal models? Give examples.


Multimodal: Process multiple input types (text, images, audio, video)

Examples:

GPT-4V: Text + images

DALL-E: Text → images

Whisper: Audio → text

CLIP: Connects text and images

Flamingo: Few-shot learning across modalities

Applications: Visual Q&A, image captioning, content moderation


Industry & Trends

11. What is the difference between OpenAI, Anthropic, and Google's AI approaches?
OpenAI: Focus on AGI, scaling laws, GPT series, commercial API focus Anthropic: Constitutional AI,
safety-first, Claude series, harmlessness emphasis
Google: Research-heavy, diverse models (PaLM, Gemini, LaMDA), integration with products Meta: Open
source focus (LLaMA), research transparency

12. What are foundation models vs specialized models?


Foundation models: Large, general-purpose models trained on broad data

Can be adapted for many tasks

Examples: GPT-4, Claude, PaLM

Specialized models: Trained for specific domains/tasks

Better performance on narrow tasks

Examples: CodeT5 (coding), BioBERT (biomedical)

Trend: Foundation models + fine-tuning replacing specialized models

13. What is the current state of AI model sizes and compute requirements?
Model size trends:

GPT-1: 117M parameters

GPT-3: 175B parameters

GPT-4: ~1.7T parameters (estimated)

PaLM: 540B parameters

Compute costs: Training largest models costs millions of dollars Trend: Focus shifting to efficiency and
smaller, capable models

14. What are some emerging AI model architectures beyond Transformers?


Mamba/State Space Models: More efficient for long sequences Mixture of Experts (MoE): Activate
only relevant parts of large models Retrieval-augmented architectures: Built-in search capabilities
Neural-symbolic: Combine neural networks with symbolic reasoning Graph Neural Networks: For
structured data

Reality: Transformers still dominant, but active research in alternatives

Business & Strategy

15. How would you choose between using APIs vs self-hosting models?
Use APIs when:

Prototype/early stage development


Unpredictable usage patterns

Need latest model capabilities

Limited ML engineering resources

Self-host when:

High volume usage (cost optimization)

Data privacy requirements

Need custom fine-tuning

Specific latency requirements

Want full control over model behavior

16. What are the key metrics for monitoring LLM applications in production?
Performance metrics:

Response time, throughput, error rates

Token usage and costs

Model quality scores

Business metrics:

User engagement, satisfaction scores

Task completion rates

Revenue impact

Safety metrics:

Harmful content detection

Bias monitoring

Hallucination rates

17. How do you handle versioning and model updates in production?


Strategies:

Blue-green deployment: Switch between two environments

Canary releases: Gradual rollout to subset of users

A/B testing: Compare old vs new model performance

Rollback plans: Quick revert if issues arise

Version pinning: Control which model version to use


Coding & Implementation

18. How would you implement caching for LLM responses?


Caching strategies:

Exact match: Cache identical prompts

Semantic similarity: Cache similar prompts using embeddings

Response templates: Cache common response patterns

Time-based expiration: Refresh cache periodically

Implementation: Redis, Memcached, or database with TTL

19. How do you handle rate limiting when using LLM APIs?
Techniques:

Exponential backoff: Increase wait time after failures

Token bucket: Allow burst usage within limits

Queue systems: Buffer requests during high load

Request batching: Combine multiple requests

Priority queuing: Handle important requests first

20. What's the difference between streaming and non-streaming responses?


Non-streaming: Wait for complete response before showing user

Pros: Can validate/filter entire response

Cons: Poor user experience for long responses

Streaming: Show response as it's generated

Pros: Better UX, feels more responsive

Cons: Harder to validate, potential for incomplete responses

Implementation: Server-Sent Events (SSE) or WebSockets

FLUTTER QUESTIONS

Basics & Fundamentals

1. What is Flutter and what are its advantages?


Flutter: Google's UI toolkit for building natively compiled applications from a single codebase.

Advantages:

Single codebase: iOS + Android + Web + Desktop

Hot reload: Fast development iteration


Native performance: Compiled to native code

Rich UI: Extensive widget library

Growing ecosystem: Strong community and packages

Disadvantages: Large app size, newer ecosystem compared to native

2. Explain the Flutter architecture?


Layers (top to bottom):

1. Framework (Dart): Widgets, rendering, animation

2. Engine (C++): Skia graphics, Dart runtime, platform channels


3. Embedder: Platform-specific code (Android, iOS)

Key insight: Flutter renders directly to canvas, bypassing native UI components

3. What is the difference between StatefulWidget and StatelessWidget?


StatelessWidget: Immutable, UI doesn't change

dart

class MyWidget extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Text('Hello World');
}
}

StatefulWidget: Can change state and rebuild UI

dart

class MyWidget extends StatefulWidget {


@override
_MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {


int counter = 0;

@override
Widget build(BuildContext context) {
return Text('Counter: $counter');
}
}
4. What is the widget tree in Flutter?
Widget tree: Hierarchical structure of widgets representing the UI

Root: MaterialApp or CupertinoApp

Branches: Layout widgets (Container, Column, Row)

Leaves: UI elements (Text, Button, Image)

Build process: Flutter traverses tree to render UI

5. Explain the build() method and when it's called?


Purpose: Returns widget tree that represents the UI Called when:

Widget is inserted into tree first time

setState() is called

Parent widget changes

InheritedWidget changes

Important: Should be pure function (same input = same output)

State Management

6. What are the different state management approaches in Flutter?


Built-in:

setState(): Local state management

InheritedWidget: Share state down widget tree

Popular packages:

Provider: Recommended by Flutter team, simple

Riverpod: Provider evolution, better testing

Bloc/Cubit: Event-driven, good for complex apps

GetX: All-in-one solution (not recommended for large apps)

Redux: Predictable state container

Choice depends on: App complexity, team size, personal preference

7. How does Provider work?


Provider: Wrapper around InheritedWidget for easier state management

Basic usage:

dart
// 1. Create provider
ChangeNotifierProvider(
create: (context) => CounterModel(),
child: MyApp(),
)

// 2. Consume in widget
Consumer<CounterModel>(
builder: (context, counter, child) {
return Text('${counter.count}');
},
)

// 3. Update state
Provider.of<CounterModel>(context, listen: false).increment();

8. What is BLoC pattern?


BLoC (Business Logic Component): Separates business logic from UI using streams

Core concepts:

Events: User interactions (ButtonPressed)

States: UI states (Loading, Success, Error)

Bloc: Transforms events into states

Benefits: Testable, reusable, predictable state changes

Navigation & Routing

9. How does navigation work in Flutter?


Navigator: Manages route stack (like browser history)

Basic navigation:

dart

// Push new route


Navigator.push(context, MaterialPageRoute(
builder: (context) => SecondScreen(),
));

// Pop current route


Navigator.pop(context);

Named routes:

dart
// Define routes
MaterialApp(
routes: {
'/': (context) => HomeScreen(),
'/second': (context) => SecondScreen(),
},
);

// Navigate using names


Navigator.pushNamed(context, '/second');

10. What is the difference between push, pushReplacement, and


pushAndRemoveUntil?
push: Add new screen to stack pushReplacement: Replace current screen with new one
pushAndRemoveUntil: Push new screen and remove screens until condition met

Use cases:

push: Normal navigation

pushReplacement: Login → Home (don't go back to login)

pushAndRemoveUntil: Reset navigation stack

Widgets & UI

11. What are the main layout widgets in Flutter?


Single child:

Container: Padding, margins, decoration

Center: Centers child widget

Padding: Adds padding around child

Multiple children:

Column: Vertical arrangement

Row: Horizontal arrangement

Stack: Overlapping widgets

ListView: Scrollable list

GridView: Grid layout

12. Explain ListView vs ListView.builder?


ListView: Creates all items at once

Good for small, fixed lists


Uses more memory
ListView.builder: Creates items on demand (lazy loading)

Good for large or dynamic lists

Memory efficient

Only builds visible items

dart

ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(title: Text(items[index]));
},
)

13. What is the difference between Container and SizedBox?


Container:

Can have decoration, padding, margins

More features but heavier

Use when you need styling

SizedBox:

Only for sizing (width, height)

Lightweight
Use when you only need spacing/sizing

dart

// For spacing
SizedBox(height: 20)

// For styling
Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(color: Colors.blue),
child: Text('Hello'),
)

Async Programming

14. How do you handle asynchronous operations in Flutter?


Future: Represents eventual result of async operation

dart
Future<String> fetchData() async {
final response = await http.get(Uri.parse('api/data'));
return response.body;
}

FutureBuilder: Widget that builds based on Future

dart

FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!);
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return CircularProgressIndicator();
},
)

15. What is the difference between Future and Stream?


Future: Single async value

One-time operation (API call)

Methods: then(), catchError(), await

Stream: Sequence of async values

Continuous data (user input, real-time updates)

Methods: listen(), map(), where()

StreamBuilder: Widget for handling streams

dart

StreamBuilder<int>(
stream: counterStream,
builder: (context, snapshot) {
return Text('${snapshot.data ?? 0}');
},
)

Performance & Optimization

16. How do you optimize Flutter app performance?


Widget optimization:
Use const constructors when possible

Avoid rebuilding expensive widgets

Use ListView.builder for large lists

Image optimization:

Use appropriate image formats

Implement image caching

Use Hero widgets for smooth transitions

Code optimization:

Minimize setState() calls

Use keys for widget identity

Profile with Flutter Inspector

17. What are keys in Flutter and when to use them?


Keys: Unique identifiers for widgets Types:

ValueKey: Based on value

ObjectKey: Based on object

UniqueKey: Always unique

GlobalKey: Access widget from anywhere

Use when: Reordering lists, maintaining state during rebuilds

dart

ListView(
children: items.map((item) => ListTile(
key: ValueKey(item.id),
title: Text(item.name),
)).toList(),
)

Platform Integration

18. How do you handle platform-specific code in Flutter?


Platform Channels: Communication bridge between Flutter and native code

Method Channel (most common):

dart
static const platform = MethodChannel('com.example/battery');

Future<String> getBatteryLevel() async {


try {
final result = await platform.invokeMethod('getBatteryLevel');
return result;
} catch (e) {
return 'Error: $e';
}
}

When to use: Native features not available in Flutter

19. How do you handle different screen sizes in Flutter?


MediaQuery: Get screen information

dart

final screenWidth = MediaQuery.of(context).size.width;


final screenHeight = MediaQuery.of(context).size.height;

Responsive design:

Flexible/Expanded: Fill available space

AspectRatio: Maintain proportions

LayoutBuilder: Build based on constraints

OrientationBuilder: Handle orientation changes

Testing

20. What types of testing can you do in Flutter?


Unit tests: Test individual functions/classes

dart

test('counter increments', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});

Widget tests: Test widget behavior

dart
testWidgets('Counter increments smoke test', (tester) async {
await tester.pumpWidget(MyApp());
expect(find.text('0'), findsOneWidget);
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
expect(find.text('1'), findsOneWidget);
});

Integration tests: Test complete app flow

Advanced Concepts

21. What are Slivers in Flutter?


Slivers: Low-level interface for scrollable areas

More control over scrolling behavior

Used inside CustomScrollView

Common slivers:

SliverAppBar: Collapsible app bar

SliverList: Efficient list

SliverGrid: Grid layout

SliverToBoxAdapter: Single widget in sliver

22. How does Flutter handle animations?


Animation types:

Implicit: Automatic animations (AnimatedContainer)

Explicit: Manual control (AnimationController)

Core classes:

AnimationController: Controls animation


Tween: Defines value range

CurvedAnimation: Apply curves

dart
class _MyWidgetState extends State<MyWidget>
with SingleTickerProviderStateMixin {
late AnimationController controller;

@override
void initState() {
controller = AnimationController(
duration: Duration(seconds: 1),
vsync: this,
);
super.initState();
}
}

23. What is the difference between hot reload and hot restart?
Hot Reload:

Preserves state

Fast (sub-second)

Updates code changes

Doesn't work with: main(), initState(), global variables

Hot Restart:

Resets state

Slower (few seconds)

Rebuilds entire app

Works with all changes

Common Interview Scenarios

24. How would you implement pull-to-refresh?

dart
RefreshIndicator(
onRefresh: _handleRefresh,
child: ListView(
children: items.map((item) => ListTile(
title: Text(item),
)).toList(),
),
)

Future<void> _handleRefresh() async {


// Fetch new data
await fetchData();
setState(() {
// Update UI
});
}

25. How do you handle form validation in Flutter?

dart

final _formKey = GlobalKey<FormState>();

Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// Process data
}
},
child: Text('Submit'),
),
],
),
)
BONUS: COMBINATION QUESTIONS (GenAI + Flutter)

1. How would you integrate a ChatGPT-like interface in Flutter?


Architecture:

dart

// State management
class ChatProvider extends ChangeNotifier {
List<Message> messages = [];

Future<void> sendMessage(String text) async {


messages.add(Message(text: text, isUser: true));
notifyListeners();

final response = await openAIService.chat(text);


messages.add(Message(text: response, isUser: false));
notifyListeners();
}
}

// UI
ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
final message = messages[index];
return ChatBubble(
text: message.text,
isUser: message.isUser,
);
},
)

2. How would you implement streaming responses from an LLM in Flutter?


Using Streams:

dart
Stream<String> streamChatResponse(String prompt) async* {
final request = http.Request('POST', Uri.parse('api/stream'));
request.headers['Content-Type'] = 'application/json';
request.body = json.encode({'prompt': prompt, 'stream': true});

final response = await request.send();


await for (String chunk in response.stream.transform(utf8.decoder)) {
// Parse Server-Sent Events
if (chunk.startsWith('data: ')) {
final data = chunk.substring(6);
if (data.trim() != '[DONE]') {
yield json.decode(data)['choices'][0]['delta']['content'] ?? '';
}
}
}
}

// In widget
StreamBuilder<String>(
stream: streamChatResponse(userMessage),
builder: (context, snapshot) {
return Text(snapshot.data ?? '');
},
)

3. How would you implement voice-to-text with AI processing in Flutter?


Integration flow:

1. Speech-to-Text: Use speech_to_text package

2. AI Processing: Send text to LLM

3. Text-to-Speech: Use flutter_tts package

dart
class VoiceAIService {
final SpeechToText _speech = SpeechToText();
final FlutterTts _tts = FlutterTts();

Future<void> startListening() async {


await _speech.listen(
onResult: (result) async {
final userText = result.recognizedWords;
final aiResponse = await processWithAI(userText);
await _tts.speak(aiResponse);
},
);
}
}

FINAL TIPS FOR SUCCESS

During the Interview:


1. Start with simple explanation, then go deeper if they want more
2. Use concrete examples - don't just give theoretical answers

3. Admit when you don't know something, but explain how you'd find out

4. Connect concepts - show how GenAI and Flutter work together

5. Ask clarifying questions - shows you think before coding

Key Phrases to Use:


"In my experience with..."

"I would approach this by..."

"The trade-off here is..."

"For production, I'd also consider..."

"Let me give you a concrete example..."

If You Get Stuck:


"That's a great question, let me think through this step by step..."

"I haven't implemented that specific case, but based on similar patterns..."

"I'd need to research the exact implementation, but the general approach would be..."

Remember: Confidence + Clear thinking + Practical examples = Success!

You've got this! 🚀

You might also like