如何在 flutter 中从动态 url 中获取 json 数据

How to fetch json data from dynamic url in flutter

我正在使用 api 给我一份膳食清单 还有用餐细节 link = https://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata

最后一个字是变量 我想知道如何解析此 link 以提供用户在搜索框中输入的膳食列表

import 'dart:async';

import 'package:_samples2/networking.dart';


const theMealDbUrl = 'https://www.themealdb.com/api/json/v1/1/search.php?s=';

class TheMealDB {
  Map<String, dynamic> data;

  FutureOr<void> fetchRecipesFor(String meal) async {
    data = await NetService.getJson<Map<String, dynamic>>('$theMealDbUrl$meal');
  }

  List<String> getMealNamesMatched() {
    return (data['meals'] as List).map<String>((m) => (m as Map)['strMeal']).toList();
  }
}

void main(List<String> args) async {
  var meals = TheMealDB();
  await meals.fetchRecipesFor('cake');
  print(meals.getMealNamesMatched());
}

结果:

[Pancakes, Rock Cakes, Carrot Cake, Dundee cake, Parkin Cake, Eccles Cakes, Madeira Cake, Christmas cake, Banana Pancakes, Battenberg Cake, New York cheesecake, Vegan Chocolate Cake, Tunisian Orange Cake, Honey Yogurt Cheesecake, Salted Caramel Cheescake, Peanut Butter Cheesecake, Provençal Omelette Cake, Polskie Naleśniki (Polish Pancakes)]

更新NetService (networking.dart)

的代码
import 'dart:convert';

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


class NetService {
  /* ---------------------------------------------------------------------------- */
  static Future<T> getJson<T>(String url) {
    return http.get(Uri.parse(url))
      .then((response) {
        if (response.statusCode == 200) {
          return jsonDecode(response.body) as T;
        }
        print('Status Code : ${response.statusCode}...');
        return null;
      })
      .catchError((err) => print(err));
  }
}