Monday, November 23, 2020

Http | DIO inFlutter

Http | Dio inFlutter

Install library
https://pub.dev/packages/http
  http: ^0.12.2

https://pub.dev/packages/dio/install
  dio: ^3.0.10

..........................................................................................................................................................................................................................................
Example :#1

httpservice.dart
import 'dart:convert';

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

class HttpService {
  final String postURL = 'https://jsonplaceholder.typicode.com/posts';

  Future<List<Post>> getPost() async {
    http.Response response = await http.get(postURL);

    if (response.statusCode == 200) {
      List<dynamic> body = jsonDecode(response.body);
      List<Post> posts = body
          .map(
            (dynamic e) => Post.fromJson(e),
          )
          .toList();
      return posts;
    } else {
      throw "Can n't get Data";
    }
  }
}
............................................
model.dart

class Post {
  Post({this.userId, this.id, this.title, this.body});

  final int userId;
  final int id;
  final String title;
  final String body;


  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'] as int,
      id: json['id'] as int,
      title: json['title'] as String,
      body: json['body'] as String,
    );
  }
}
home.dart

import 'package:demo/services/http_service.dart';
import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  final HttpService httpService = HttpService();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Screens'),
        centerTitle: true,
      ),
      body: FutureBuilder(
        future: httpService.getPost(),
        builder: (context, AsyncSnapshot<List<Post>> snapshot) {
          if (snapshot.hasData) {
            List<Post> posts = snapshot.data;
            return ListView(
              children: posts
                  .map((Post e) => ListTile(
                        title: Text(e.title),
                        subtitle: Text('${e.userId}'),
                      ))
                  .toList(),
            );
          } else {
            return CircularProgressIndicator();
          }
        },
      ),
    );
  }
}

....................................
main.dart

import 'package:demo/screens/home.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
      
    );
  }
}
 Happy Coding :)
..........................................................................................................................................................................................................................................
Example :#2 [ Basic way Fetch Data from Api ]

import 'dart:convert';

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  final String Base_Url = 'https://jsonplaceholder.typicode.com/todos';

  Future<List<User>> getData() async {
    http.Response response = await http.get(Base_Url);
    if (response.statusCode == 200) {
      List<dynamic> body = jsonDecode(response.body);
      List<User> user = body.map((e) => User.fromJson(e)).toList();
      return user;
    } else {
      throw "Can't get Data";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: FutureBuilder(
          future: getData(),
          builder: (context, AsyncSnapshot<List<User>> snapshot) {
            if (snapshot.hasData) {
              List<User> user = snapshot.data;
              return ListView(
                  children: user
                      .map((e) => Card(
                        elevation: 20,
                        shape: StadiumBorder(),
                            child: ListTile(
                              title: Text('${e.id}'),
                              subtitle: Text(e.title),
                            ),
                          ))
                      .toList());
            } else {
              return CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}

class User {
  User({this.id, this.userid, this.body, this.title});
  int userid;
  int id;
  String body;
  String title;

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
        userid: json['userid'],
        id: json['id'],
        title: json['title'],
        body: json['body']);
  }
}
Happy Coding :)
..........................................................................................................................................................................................................................................
Example :#3 [ How to Send data from flutter app to MySQL Database ]

1. Now we will create a function for sending data into mysql

Future<List> senddata() async {
  final response = await http.post("http://raushanjha.in/insertdata.php", body: {
    "name": user.text,
    "email": pass.text,
    "mobile":mobile.text,
  });

  var datauser = json.decode(response.body);
or

Future getData() async{
    var url = 'https://disgusted-vapors.000webhostapp.com/get.php';
    http.Response response = await http.get(url);
    var data = jsonDecode(response.body);
    print(data.toString());
  }

Or
@override
  void initState() {
    getData();
  }




2.Complete Code of main.dart file

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

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

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

String username='';

class MyApp extends StatelessWidget {
  
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter App with MYSQL',     
      home: new MyHomePage(),
     
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

TextEditingController name=new TextEditingController();
TextEditingController email=new TextEditingController();
TextEditingController mobile=new TextEditingController();

Future<List> senddata() async {
  final response = await http.post("http://raushanjha.in/insertdata.php", body: {
    "name": name.text,
    "email": email.text,
    "mobile":mobile.text,
  });
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Register"),),
      body: Container(
        child: Center(
          child: Column(
            children: <Widget>[
              Text("Username",style: TextStyle(fontSize: 18.0),),
              TextField(   
                controller: name,                
                decoration: InputDecoration(
                  hintText: 'name'
                ),           
                ),
              Text("Email",style: TextStyle(fontSize: 18.0),),
              TextField(  
                controller: email,      
                 decoration: InputDecoration(
                  hintText: 'Email'
                ),                
                ),
                Text("Mobile",style: TextStyle(fontSize: 18.0),),
              TextField(  
                controller: mobile,        
                 decoration: InputDecoration(
                  hintText: 'Mobile'
                ),                
                ),
              
              RaisedButton(
                child: Text("Register"),
                onPressed: (){
                  senddata;
                },
              ),

            ],
          ),
        ),
      ),
    );
}
}
Happy Coding :)
..........................................................................................................................................................................................................................................
Example :#4 [ Flutter + Larael ]
..........................
dependencies:   
  shared_preferences: ^0.5.12+4
  http: ^0.12.2

https://pub.dev/packages/shared_preferences/install
https://pub.dev/packages/http/install

Note: You could also choose to handle data storage with SQLite or Hive packages especially for large data structures.
..........................
..........................




Happy Coding :)
..........................................................................................................................................................................................................................................
Example :#5[ json Placeholder ]

import 'dart:convert';

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

final _baseUrl = 'jsonplaceholder.typicode.com';
final String _todos = '/todos';

class QuoteApiClient {
  Future<List<Post>> fetchPost() async {
    String uri = 'https://jsonplaceholder.typicode.com/todos';
   // Uri uri = Uri.https(_baseUrl, _todos);
    http.Response response = await http.get(uri);

    if (response.statusCode == 200) {
      List<Post> post = postFromJson(response.body);
      return post;
    } else {
      throw new Exception('Error');
    }
  }
}
..................................................
import 'package:flutter/material.dart';
import 'package:newproject/services/service.dart';

import 'models/models.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
   QuoteApiClient quoteApiClient = QuoteApiClient();
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Http'),
        centerTitle: true,
      ),
      body: Container(
        child: FutureBuilder(
          future: widget.quoteApiClient.fetchPost(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  Post post = snapshot.data[index];
                  return Text('${post.title}');
                },
              );
            }
            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

Happy Coding :)
..........................................................................................................................................................................................................................................
Example :#6



Happy Coding :)










No comments:

Post a Comment