Creare un carousel in Flutter

Mattepuffo's logo
Creare un carousel in Flutter

Creare un carousel in Flutter

In questo articolo vediamo come creare un carousel in Flutter senza usare librerie esterne.

Useremo il widget PageView, e le immagini le prenderemo online.

Qui sotto il codice completo:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late PageController _pageController;
  int _activePage = 0;
  List<String> immagini = [
    "https://picsum.photos/id/0/5000/3333",
    "https://picsum.photos/id/1/5000/3333",
    "https://picsum.photos/id/2/5000/3333",
    "https://picsum.photos/id/3/5000/3333",
    "https://picsum.photos/id/4/5000/3333",
    "https://picsum.photos/id/5/5000/3334",
    "https://picsum.photos/id/6/5000/3333",
  ];

  @override
  void initState() {
    super.initState();
    _pageController = PageController(viewportFraction: 0.8);
  }

  @override
  Widget build(BuildContext context) {
    return PageView.builder(
      itemCount: immagini.length,
      pageSnapping: true,
      controller: _pageController,
      onPageChanged: (page) {
        setState(() {
          _activePage = page;
        });
      },
      itemBuilder: (ctx, pagePosition) {
        return Container(
          margin: const EdgeInsets.all(10),
          child: Image.network(immagini[pagePosition]),
        );
      },
    );
  }
}

Enjoy!


Condividi

Commentami!