Sunday, May 28, 2017

An Example of Flutter ListView and url_launcher

This mobile app reads a list of MP3 files that was encoded in JSON, and lists them on the cellphone's screen. Tapping on a list item triggers a website that plays that song back.

This Dart's dependencies were configured in pubspec.yaml as follows:

dependencies:
  http: any
  flutter:
    sdk: flutter
  url_launcher:

url_launcher is a Flutter plugin created by Google. My guess is they wanted to standardize mobile app browser launching. Here is an example of JSON this code consumes:

{"songs":["Doused.mp3","Peace_of_Mind.mp3","Siobhan.mp3","Slowdive - Souvlaki - 03 - 40 Days.mp3","When the Sun Hits.mp3"]}

Here is lib/main.dart, in all its glory:

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

List<String> songFileNames = new List();

loadSongFileNames() async {
  http.Response response = await http.get('http://10.0.0.6:8080/api/filelist');
  String body = response.body;
  var json = JSON.decode(body);
  for (var song in json['songs']) {
    songFileNames.add(song);
  }
}

main() async {
  await loadSongFileNames();
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
//  final List<String> songFileNames = ['flutter.io', 'dartlang.org', 'golang.org'];
  List<ListTile> _getList() {
    List<ListTile> list = new List();
    for (var song in songFileNames) {
      ListTile tile = new ListTile(
        title: new Text(song),
        onTap: () {
          launch('http://10.0.0.6:8000/?song=$song');
        },


      );
      list.add(tile);
    }
    return list;
  }

  @override  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Scaffold(
        appBar: new AppBar(title: new Text('My Songs'),),
        body: new ListView(
          children: _getList(),
        ),
      ),
    );
  }
}

No comments:

Post a Comment