Introduction à Flutter

Flutter est un framework de Google pour créer des applications natives multiplateformes avec Dart.

Configuration

# Installation
# 1. Télécharger Flutter SDK
# 2. Ajouter flutter/bin au PATH

# Vérifier l'installation
flutter doctor

# Créer un projet
flutter create mon_app
cd mon_app

# Structure du projet
mon_app/
├── lib/
│   ├── main.dart
│   ├── screens/
│   ├── widgets/
│   └── models/
├── assets/
├── test/
├── android/
├── ios/
└── pubspec.yaml

# Lancer l'application
flutter run

Application de base

// lib/main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Mon Application',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Accueil'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'Bienvenue sur Flutter!',
              style: TextStyle(fontSize: 24),
            ),
            ElevatedButton(
              onPressed: () {
                // Action
              },
              child: const Text('Cliquez ici'),
            ),
          ],
        ),
      ),
    );
  }
}

Widgets et État

StatelessWidget

class CustomCard extends StatelessWidget {
  final String title;
  final String description;

  const CustomCard({
    required this.title,
    required this.description,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Text(
              title,
              style: Theme.of(context).textTheme.headline6,
            ),
            const SizedBox(height: 8),
            Text(description),
          ],
        ),
      ),
    );
  }
}

StatefulWidget

class Counter extends StatefulWidget {
  const Counter({Key? key}) : super(key: key);

  @override
  State createState() => _CounterState();
}

class _CounterState extends State {
  int _count = 0;

  void _increment() {
    setState(() {
      _count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(
          'Count: $_count',
          style: const TextStyle(fontSize: 24),
        ),
        ElevatedButton(
          onPressed: _increment,
          child: const Text('Incrémenter'),
        ),
      ],
    );
  }
}

Navigation

// Routes nommées
MaterialApp(
  initialRoute: '/',
  routes: {
    '/': (context) => HomeScreen(),
    '/details': (context) => DetailsScreen(),
    '/settings': (context) => SettingsScreen(),
  },
);

// Navigation
Navigator.pushNamed(
  context,
  '/details',
  arguments: {'id': 123},
);

// Récupérer les arguments
class DetailsScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final args = ModalRoute.of(context)!.settings
        .arguments as Map;

    return Scaffold(
      appBar: AppBar(title: Text('Details')),
      body: Text('ID: ${args['id']}'),
    );
  }
}

Fonctionnalités natives

// Caméra
import 'package:camera/camera.dart';

Future initCamera() async {
  final cameras = await availableCameras();
  final camera = cameras.first;
  controller = CameraController(
    camera,
    ResolutionPreset.medium,
  );
  await controller.initialize();
}

// Géolocalisation
import 'package:geolocator/geolocator.dart';

Future getLocation() async {
  bool serviceEnabled =
    await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    return Future.error('Location disabled');
  }

  LocationPermission permission =
    await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator
      .requestPermission();
  }

  return await Geolocator.getCurrentPosition();
}