Flutter Code Snippets
Flutter snippets Β· Ready to use
Build faster with practical Flutter code
Choose a pattern, copy it into your project, and make it your own. Each example is a focused starting point for real apps.
Responsive two-column layout
Switch between side-by-side panels on wider screens and stacked panels on phones.
LayoutBuilder(
builder: (context, constraints) {
final isWide = constraints.maxWidth >= 700;
if (isWide) {
return Row(
children: [
Expanded(child: ProfilePanel()),
Expanded(child: DetailsPanel()),
],
);
}
return Column(
children: [ProfilePanel(), DetailsPanel()],
);
},
)
Grid that adapts to available width
Show more cards per row on wider screens while keeping the layout compact on phones.
LayoutBuilder(
builder: (context, constraints) {
final columns = constraints.maxWidth >= 700 ? 3 : 2;
return GridView.count(
crossAxisCount: columns,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
children: products
.map((product) => ProductCard(product: product))
.toList(),
);
},
)
Loading, success, and error states
Handle the common states of a request in one place with FutureBuilder.
FutureBuilder<User>(
future: userFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return const Text('Could not load user');
}
if (!snapshot.hasData) {
return const Text('No user found');
}
return Text('Hello, ${snapshot.data!.name}');
},
)
Display a live stream
Render incoming updates and handle loading, errors, and empty results with StreamBuilder.
StreamBuilder<List<Message>>(
stream: messagesStream,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text('Could not load messages');
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.data!.isEmpty) {
return const Text('No messages yet');
}
return ListView(
children: snapshot.data!
.map((message) => ListTile(title: Text(message.text)))
.toList(),
);
},
)
Validate before saving
Keep input checks near their fields and save only after the form passes validation.
final formKey = GlobalKey<FormState>();
Form(
key: formKey,
child: TextFormField(
decoration: const InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || !value.contains('@')) {
return 'Enter a valid email';
}
return null;
},
),
)
if (formKey.currentState!.validate()) {
saveProfile();
}
Require a selection
Validate a dropdown field so the form cannot be submitted without a category.
DropdownButtonFormField<String>(
value: selectedCategory,
decoration: const InputDecoration(labelText: 'Category'),
items: categories
.map(
(category) => DropdownMenuItem(
value: category,
child: Text(category),
),
)
.toList(),
validator: (value) =>
value == null ? 'Choose a category' : null,
onChanged: (value) {
setState(() => selectedCategory = value);
},
)
Send a chat request with Gemini
Keep the API key on a trusted server in production; this client example assumes a configured service.
final response = await GeminiService.instance.generateContent(
'Suggest three names for a plant care app.',
);
final answer = response.text ?? 'No response received';
Parse structured AI output safely
Ask for JSON, then validate fields before using model generated values.
final decoded = jsonDecode(response.text!) as Map<String, dynamic>;
final title = decoded['title'];
final score = decoded['score'];
if (title is String && score is num) {
showSuggestion(title, score.toDouble());
}
Add a retry limit to AI requests
Retry transient failures with a short delay and stop after a fixed number of attempts.
Future<T> retryAiRequest<T>(Future<T> Function() request) async {
const maxAttempts = 3;
for (var attempt = 0; ; attempt++) {
try {
return await request();
} catch (_) {
if (attempt + 1 >= maxAttempts) rethrow;
await Future<void>.delayed(
Duration(milliseconds: 300 * (attempt + 1)),
);
}
}
}