Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

fetch data flutter json

import 'dart:async';
import 'dart:convert';

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

Future<Album> fetchAlbum() async {
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

class Album {
  final int userId;
  final int id;
  final String title;

  const Album({
    required this.userId,
    required this.id,
    required this.title,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late Future<Album> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Album>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data!.title);
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }

              // By default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
Comment

how to fetch data from json file in flutter

import 'dart:convert';

main() {
  String jsonS = """{
    "stream": {
        "tv": [{
            "name": "Tv",
            "description": "Tv",
            "url": "this is the url",
            "image": "imagelink"

        }]
    }
}""";
  var myMap = json.decode(jsonS);
  var myName = myMap['stream']['tv'][0]['name'];
  print('${myName}');
}
Comment

flutter fetch data from api example

Future<int> getSettings(int i) async {
    final url = Uri.parse(ApiLinks.settingsUrl + "/settings");

    try {
      http.Response response = await http.get(url,
          headers: {
            'Authorization': ApiLinks.token
          });
      if (response.statusCode == 200) {

        var  res = jsonDecode(response.body);
        //print(" res = "+res.toString());
        print(" res0 = "+res["StatusMessage"][i]["value_setting"].toString());
        return res["StatusMessage"][i]["value_setting"];
      }
      return 0;
    } catch (e) {
      print("Settings Api Get, error occurred " + e.toString());
      return 0;
    }
  }
Comment

PREVIOUS NEXT
Code Example
Javascript :: Shuffle a Sting in JavaScript 
Javascript :: ngchange angular 8 
Javascript :: slicknav cdn 
Javascript :: new jsonobject java 
Javascript :: ReferenceError: Buffer is not defined 
Javascript :: javascript parse json string 
Javascript :: js classlist 
Javascript :: angular checkbox disabled 
Javascript :: Get the Status Code of a Fetch HTTP Response 
Javascript :: hardhat test 
Javascript :: flutter http request 
Javascript :: regex match word inside string 
Javascript :: nodejs download image from url 
Javascript :: get message author discord.js 
Javascript :: sequelize not equal 
Javascript :: encodeuricomponent js 
Javascript :: get last element in array in js 
Javascript :: js add element to front of array 
Javascript :: how to remove an element from a parent element javascript 
Javascript :: node command line input 
Javascript :: Vue use props in style 
Javascript :: angular serve 
Javascript :: ecmascript compose 
Javascript :: insert into specific array index 
Javascript :: import all images from folder reactjs 
Javascript :: body click function removeclass 
Javascript :: react disable eslint errors 
Javascript :: react native no android sdk found 
Javascript :: javascript try 
Javascript :: sort array of object by another value array in javascript 
ADD CONTENT
Topic
Content
Source link
Name
5+1 =