API CALL

  • Screen 1

    main.dart

    
                  import 'package:flutter/material.dart';
    import 'package:b/dictionary_screen.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
    
          home: DictionaryHomePage(),
          debugShowCheckedModeBanner: false,
        );
      }
    }
    
    

    services.dart

    
    import 'dart:convert';
    
    import 'package:http/http.dart' as http;
    
    import 'dictionary_model.dart';
    
    class APIservices {
      static String baseUrl = "https://api.dictionaryapi.dev/api/v2/entries/en/";
      static Future<DictionaryModel?> fetchData(String word) async {
        Uri url = Uri.parse("$baseUrl$word");
        final response = await http.get(url);
        try {
          if (response.statusCode == 200) {
            final data = json.decode(response.body);
            return DictionaryModel.fromJson(data[0]);
          } else {
            throw Exception("Filure to load meaning ");
          }
        } catch (e) {
          print(e.toString());
        }
        return null;
      }
    }
    
    

    dictionary_model.dart

    
    
    // To parse this JSON data, do
    //
    //     final dictionaryModel = dictionaryModelFromJson(jsonString);
    
    import 'dart:convert';
    
    List<DictionaryModel> dictionaryModelFromJson(String str) =>
        List<DictionaryModel>.from(
            json.decode(str).map((x) => DictionaryModel.fromJson(x)));
    
    String dictionaryModelToJson(List<DictionaryModel> data) =>
        json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class DictionaryModel {
      String word;
      List<Phonetic> phonetics;
      List<Meaning> meanings;
      License license;
      List<String> sourceUrls;
    
      DictionaryModel({
        required this.word,
        required this.phonetics,
        required this.meanings,
        required this.license,
        required this.sourceUrls,
      });
    
      factory DictionaryModel.fromJson(Map<String, dynamic> json) =>
          DictionaryModel(
            word: json["word"],
            phonetics: List<Phonetic>.from(
                json["phonetics"].map((x) => Phonetic.fromJson(x))),
            meanings: List<Meaning>.from(
                json["meanings"].map((x) => Meaning.fromJson(x))),
            license: License.fromJson(json["license"]),
            sourceUrls: List<String>.from(json["sourceUrls"].map((x) => x)),
          );
    
      Map<String, dynamic> toJson() => {
        "word": word,
        "phonetics": List<dynamic>.from(phonetics.map((x) => x.toJson())),
        "meanings": List<dynamic>.from(meanings.map((x) => x.toJson())),
        "license": license.toJson(),
        "sourceUrls": List<dynamic>.from(sourceUrls.map((x) => x)),
      };
    }
    
    class License {
      String name;
      String url;
    
      License({
        required this.name,
        required this.url,
      });
    
      factory License.fromJson(Map<String, dynamic> json) => License(
        name: json["name"],
        url: json["url"],
      );
    
      Map<String, dynamic> toJson() => {
        "name": name,
        "url": url,
      };
    }
    
    class Meaning {
      String partOfSpeech;
      List<Definition> definitions;
      List<String> synonyms;
      List<String> antonyms;
    
      Meaning({
        required this.partOfSpeech,
        required this.definitions,
        required this.synonyms,
        required this.antonyms,
      });
    
      factory Meaning.fromJson(Map<String, dynamic> json) => Meaning(
        partOfSpeech: json["partOfSpeech"],
        definitions: List<Definition>.from(
            json["definitions"].map((x) => Definition.fromJson(x))),
        synonyms: List<String>.from(json["synonyms"].map((x) => x)),
        antonyms: List<String>.from(json["antonyms"].map((x) => x)),
      );
    
      Map<String, dynamic> toJson() => {
        "partOfSpeech": partOfSpeech,
        "definitions": List<dynamic>.from(definitions.map((x) => x.toJson())),
        "synonyms": List<dynamic>.from(synonyms.map((x) => x)),
        "antonyms": List<dynamic>.from(antonyms.map((x) => x)),
      };
    }
    
    class Definition {
      String definition;
      List<dynamic> synonyms;
      List<dynamic> antonyms;
      String? example;
    
      Definition({
        required this.definition,
        required this.synonyms,
        required this.antonyms,
        this.example,
      });
    
      factory Definition.fromJson(Map<String, dynamic> json) => Definition(
        definition: json["definition"],
        synonyms: List<dynamic>.from(json["synonyms"].map((x) => x)),
        antonyms: List<dynamic>.from(json["antonyms"].map((x) => x)),
        example: json["example"],
      );
    
      Map<String, dynamic> toJson() => {
        "definition": definition,
        "synonyms": List<dynamic>.from(synonyms.map((x) => x)),
        "antonyms": List<dynamic>.from(antonyms.map((x) => x)),
        "example": example,
      };
    }
    
    class Phonetic {
      String audio;
      String? sourceUrl;
      License? license;
      String? text;
    
      Phonetic({
        required this.audio,
        this.sourceUrl,
        this.license,
        this.text,
      });
    
      factory Phonetic.fromJson(Map<String, dynamic> json) => Phonetic(
        audio: json["audio"],
        sourceUrl: json["sourceUrl"],
        license:
        json["license"] == null ? null : License.fromJson(json["license"]),
        text: json["text"],
      );
    
      Map<String, dynamic> toJson() => {
        "audio": audio,
        "sourceUrl": sourceUrl,
        "license": license?.toJson(),
        "text": text,
      };
    }
    
    
    
    

    dictionary_screen.dart

    
    import 'package:b/dictionary_model.dart';
    import 'package:flutter/material.dart';
    
    import 'services.dart';
    
    class DictionaryHomePage extends StatefulWidget {
      const DictionaryHomePage({super.key});
    
      @override
      State<DictionaryHomePage> createState() => _DictionaryHomePageState();
    }
    
    class _DictionaryHomePageState extends State<DictionaryHomePage> {
      DictionaryModel? myDictionaryModel;
      bool isLoading = false;
      String noDataFound = " Now You Can Search";
    
      searchContain(String word) async {
        setState(() {
          isLoading = true;
        });
        try {
          myDictionaryModel = await APIservices.fetchData(word);
          setState(() {});
        } catch (e) {
          myDictionaryModel = null;
          noDataFound = "Meaning can't be found";
        } finally {
          setState(() {
            isLoading = false;
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text("Dictionary"),
          ),
          body: Padding(
            padding: const EdgeInsets.all(15),
            child: Column(
              children: [
                // for searching the word
                SearchBar(
                  hintText: "Search the word here",
                  onSubmitted: (value) {
                    searchContain(value);
                  },
                ),
                const SizedBox(height: 10),
                if (isLoading)
                  const LinearProgressIndicator()
                else if (myDictionaryModel != null)
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(height: 15),
                        Text(
                          myDictionaryModel!.word,
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 25,
                            color: Colors.blue,
                          ),
                        ),
                        Text(
                          myDictionaryModel!.phonetics.isNotEmpty
                              ? myDictionaryModel!.phonetics[0].text ?? ""
                              : "",
                        ),
                        const SizedBox(height: 10),
                        Expanded(
                          child: ListView.builder(
                            itemCount: myDictionaryModel!.meanings.length,
                            itemBuilder: (context, index) {
                              return showMeaning(
                                  myDictionaryModel!.meanings[index]);
                            },
                          ),
                        ),
                      ],
                    ),
                  )
                else
                  Center(
                    child: Text(
                      noDataFound,
                      style: const TextStyle(fontSize: 22),
                    ),
                  ),
              ],
            ),
          ),
        );
      }
    
      showMeaning(Meaning meaning) {
        String wordDefination = "";
        for (var element in meaning.definitions) {
          int index = meaning.definitions.indexOf(element);
          wordDefination += "\n${index + 1}.${element.definition}\n";
        }
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 10),
          child: Material(
            elevation: 2,
            borderRadius: BorderRadius.circular(20),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    meaning.partOfSpeech,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 22,
                      color: Colors.blue,
                    ),
                  ),
                  const SizedBox(height: 10),
                  const Text(
                    "Definations : ",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                      color: Colors.black,
                    ),
                  ),
                  Text(
                    wordDefination,
                    style: const TextStyle(
                      fontSize: 16,
                      height: 1,
                    ),
                  ),
                  wordRelation("Synonyms", meaning.synonyms),
                  wordRelation("Antonyms", meaning.antonyms),
    
                ],
              ),
            ),
          ),
        );
      }
    
      wordRelation(String title, List<String>? setList) {
        if (setList?.isNotEmpty ?? false) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "$title : ",
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 18,
                ),
              ),
              Text(
                setList!.toSet().toString().replaceAll("{", "").replaceAll("}", ""),
                style: const TextStyle(fontSize: 18),
              ),
              const SizedBox(height: 10),
            ],
          );
        } else {
          return const SizedBox();
        }
      }
    }