0

I have a question about json in flutter. How can I make an api request.

there is an approximate data that is in the template. but I need to take it through url. I tried many examples that are here, but I still haven't figured it out.

Posts are taken for both Russian and English.

    class DummyPosts{
    
      static final Map<String, List<Post>> posts = {
        'ru': _ru,
        "en": _en,
      };
    
      static final List<Post> _ru = [
        Post(
          id: 1,
          title: 'Apple expands renewable energy footprint in Europe',
          thumbnail:
          'https://www.apple.com/newsroom/images/values/environment/apple_eu-renewable-energy-expansion_wind-farm_09012020_big.jpg.large_2x.jpg',
          excerpt: 'World’s largest onshore wind turbines in Denmark and new clean energy efforts in Germany advance Apple’s new 2030 carbon neutral goal',
          category: 'Tech',
          views: 456,
          comments: 23,
          htmlContent: '<p>Today Apple announced it will invest in the construction of two of the world’s largest onshore wind turbines, a source of clean, renewable energy that will bring its supply chain and products one step closer to carbon neutrality. Located near the Danish town of Esbjerg, the 200-meter-tall turbines are expected to produce 62 gigawatt hours each year — enough to power almost 20,000 homes — and will act as a test site for powerful offshore wind turbines. The power produced at Esbjerg will support Apple’s data center in Viborg, with all surplus energy going into the Danish grid.</p>',
          tags: [
            Tag(id: 1, name: 'Post'),
            Tag(id: 2, name: 'News'),
            Tag(id: 3, name: 'Tech'),
            Tag(id: 4, name: 'Apple'),
          ],
          createdAt: DateTime.now().subtract(Duration(days: 900)),
        ),
];

  static final List<Post> _en = [
    Post(
      id: 1,
      title: 'Apple expands renewable energy footprint in Europe',
      thumbnail:
          'https://www.apple.com/newsroom/images/values/environment/apple_eu-renewable-energy-expansion_wind-farm_09012020_big.jpg.large_2x.jpg',
      excerpt: 'World’s largest onshore wind turbines in Denmark and new clean energy efforts in Germany advance Apple’s new 2030 carbon neutral goal',
      category: 'Tech',
      views: 456,
      comments: 23,
      htmlContent: '<p>Today Apple announced it will invest in the construction of two of the world’s largest onshore wind turbines, a source of clean, renewable energy that will bring its supply chain and products one step closer to carbon neutrality. Located near the Danish town of Esbjerg, the 200-meter-tall turbines are expected to produce 62 gigawatt hours each year — enough to power almost 20,000 homes — and will act as a test site for powerful offshore wind turbines. The power produced at Esbjerg will support Apple’s data center in Viborg, with all surplus energy going into the Danish grid.</p>',
      tags: [
        Tag(id: 1, name: 'Post'),
        Tag(id: 2, name: 'News'),
        Tag(id: 3, name: 'Tech'),
        Tag(id: 4, name: 'Apple'),
      ],
      createdAt: DateTime.now().subtract(Duration(days: 900)),
    ),
];

Model

class Post{
  int id;
  String title;
  String excerpt;
  String thumbnail;
  String category;
  int views;
  int comments;
  String htmlContent;
  List<Tag> tags;
  DateTime createdAt;

  Post({
    this.id,
    this.title,
    this.excerpt,
    this.thumbnail,
    this.category,
    this.views,
    this.comments,
    this.htmlContent,
    this.tags,
    this.createdAt,
  });


}

Sorry for my English.

2 Answers 2

2

1. Prerequisites

Add http package

dependencies:
  http: <latest_version>

Import the http package

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

Add in your AndroidManifest.xml the Internet permission

<uses-permission android:name="android.permission.INTERNET" />

2. Make a network request

Future<http.Response> fetchPosts(String lang) {
  return http.get(Uri.https('api-url.com', 'posts', {'lang': lang}));
}

3. Convert to object

class Post{
  int id;
  String title;
  String excerpt;
  String thumbnail;
  String category;
  int views;
  int comments;
  String htmlContent;
  List<Tag> tags;
  DateTime createdAt;

  Post({
    this.id,
    this.title,
    this.excerpt,
    this.thumbnail,
    this.category,
    this.views,
    this.comments,
    this.htmlContent,
    this.tags,
    this.createdAt,
  });
  
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'],
      // ... and other attr
    );
  }
}

final response1 = await fetchPosts("en");
final response2 = await fetchPosts("ru");
final List<Post> enPosts = response1.body.map((i) => Post.fromJson(i)).toList();
final List<Post> ruPosts = response2.body.map((i) => Post.fromJson(i)).toList();

UPD:

I would add something like this in your case

Future<Map<String, List<Post>>> getPosts() async {
    final response1 = await fetchPosts("en");
    final response2 = await fetchPosts("ru");
    final List<Post> enPosts = response1.body.map((i) => Post.fromJson(i)).toList();
    final List<Post> ruPosts = response2.body.map((i) => Post.fromJson(i)).toList();
    return {
      "en": enPosts,
      'ru': ruPosts,
    };
  }

Instead of

static final Map<String, List<Post>> posts = {
    'ru': _ru,
    "en": _en,
  };
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much for the help. But could you please explain where I should insert this, tk. I do not quite understand. I'm just learning flutter
@rostvlan I can post a template. could you help with 1 example, post. drive.google.com/file/d/1-xuqfxZO0lXzJTEWwiPczieq3AUbLPIR/…
0

May I suggest you check out using chopper and json annotation to manage your requests? ResoCoder has an excellent series of three videos and accompanything posts over at https://resocoder.com/2019/06/19/chopper-retrofit-for-flutter-basics/ that will guide you through the process.

It's a little bit more work to get it started but I think it will save you effort in the long term.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.