Flutter Cheat Sheet
Hello World:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Hello, World!'),
),
body: Center(
child: Text('Hello, World!'),
),
),
));
}
Widgets:
// Container
Container(
color: Colors.blue,
width: 200,
height: 200,
child: Text('Container Widget'),
)
// Text
Text(
'Hello, World!',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
)
// Image
Image.network(
'https://example.com/image.jpg',
)
// Column
Column(
children: [
Text('First Widget'),
Text('Second Widget'),
],
)
// Row
Row(
children: [
Text('First Widget'),
Text('Second Widget'),
],
)
// Button
ElevatedButton(
onPressed: () {
// Code to execute when the button is pressed
},
child: Text('Click Me'),
)
State Management:
// Stateful Widget
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State {
int counter = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Counter: $counter'),
ElevatedButton(
onPressed: () {
setState(() {
counter++;
});
},
child: Text('Increment'),
),
],
);
}
}
// Using the Stateful Widget
MyWidget()
Navigating Between Screens:
// Navigation
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
// Second Screen
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Screen'),
),
body: Center(
child: Text('Welcome to the Second Screen!'),
),
);
}
}
Networking:
import 'package:http/http.dart' as http;
// GET Request
http.get(Uri.parse('https://example.com/api/data'))
.then((response) {
if (response.statusCode == 200) {
// Process the response
print(response.body);
} else {
// Handle error
print('Request failed with status: ${response.statusCode}');
}
});
// POST Request
http.post(Uri.parse('https://example.com/api/data'),
body: {'name': 'John', 'age': '25'})
.then((response) {
if (response.statusCode == 200) {
// Process the response
print(response.body);
} else {
// Handle error
print('Request failed with status: ${response.statusCode}');
}
});
Animations:
import 'package:flutter/animation.dart';
// Animated Container
AnimatedContainer(
duration: Duration(seconds: 1),
width: 200,
height: 200,
color: Colors.blue,
)
// Tween Animation
AnimationController controller;
Animation animation;
controller = AnimationController(
duration: Duration(seconds: 1),
vsync: this,
);
animation = Tween(begin: 0, end: 1).animate(controller);
// Start the animation
controller.forward();