Hämta JSON-data

Skapa en klass för datat du vill ha.

class Data {
  final String col1;
  final String col2;

  Data({this.col1, this.col2});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      col1: json['col1'],
      col2: json['col2']
    );
  }
}

Hämta och parsa.

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'data.dart';

Future<String> fetchData(String url) async {
  final response = await http.get(url);

  if (response.statusCode == 200) {
    return response.body;
  } else {
    throw Exception('HTTP error' + response.statusCode.toString());
  }
}

Future<List<Data>> getJsondata(String url) async {
  final response = await fetchData(url);
  final parsed = json.decode(response).cast<Map<String, dynamic>>();
  return parsed.map<Data>((json) => Data.fromJson(json)).toList();
}

Lämna ett svar

Stäng meny