Link preview in Flutter

Mattepuffo's logo
Link preview in Flutter

Link preview in Flutter

In questo articolo vogliamo ottenere una sorta di link preview stile Google nella nostra app Flutter.

Per farlo abbiamo una libreria apposita: simple_url_preview!

Aggiungete la dipendenza al pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  simple_url_preview: ^3.0.1

Qui sotto un pò di codice di esempio:

import 'package:flutter/material.dart';
import 'package:simple_url_preview/simple_url_preview.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(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  final String _url = "https://github.com/mattepuffo";

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SimpleUrlPreview(
            url: _url,
            titleLines: 2,
            descriptionLines: 3,
            imageLoaderColor: Colors.black,
            previewHeight: 500,
            previewContainerPadding: const EdgeInsets.all(10),
            titleStyle: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Colors.black26,
            ),
            descriptionStyle: TextStyle(
              fontSize: 14,
              color: Theme.of(context).primaryColor,
            ),
            siteNameStyle: TextStyle(
              fontSize: 14,
              color: Theme.of(context).primaryColor,
            ),
          ),
        ],
      ),
    );
  }
}

Enjoy!


Condividi su Facebook

Commentami!