Thursday, December 17, 2020

Onboarding UI Screen || Slider

 Onboarding UI Screen

...........................................................................................................................................................................................................................
Example :#1 []

Install Library

https://pub.dev/packages/introduction_screen/install
  introduction_screen: ^1.0.9

Code Here

import 'package:flutter/material.dart';
import 'package:introduction_screen/introduction_screen.dart';

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

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

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: IntroductionScreen(
        pages: [
          PageViewModel(
            title: 'A reader lives a thousand lives',
            body: 'The man who never reads lives only one',
            image: buildImage('assets/images/dog.jpg'),
            decoration: getDecorations(),
          ),
          PageViewModel(
            title: 'A reader lives a thousand lives',
            body: 'The man who never reads lives only one',
            image: buildImage('assets/images/dog.jpg'),
            decoration: getDecorations(),
          ),
          PageViewModel(
            title: 'A reader lives a thousand lives',
            body: 'The man who never reads lives only one',
            image: buildImage('assets/images/dog.jpg'),
            decoration: getDecorations(),
          ),
        ],
        done: Text('Read'),
        onDone: () {},
        showSkipButton: true,
        skip: Text('Skip'),
        skipFlex: 0,
        nextFlex: 0,
        next: Icon(Icons.arrow_forward),
        dotsDecorator: gotdotsDecorator(),
       // isProgress: false, //bubble disappear
       // isProgressTap: false, // Bubble will be not work if click
        //showNextButton: false,
        //freeze: true,  // user cannot swip left or right
        animationDuration: 1000,  //button will be work

      ),
    );
  }

  Widget buildImage(String path) {
    return Center(
      child: Image.asset(path, width: 450),
    );
  }

  PageDecoration getDecorations() {
    return PageDecoration(
        titleTextStyle: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
        bodyTextStyle: TextStyle(fontSize: 25),
        descriptionPadding: EdgeInsets.all(16).copyWith(bottom: 0),
        imagePadding: EdgeInsets.all(24),
        pageColor: Colors.white);
        
  }

  DotsDecorator gotdotsDecorator() {
    return DotsDecorator(
      activeColor: Colors.orange,
      size: Size(15, 15),
      activeSize: Size(22,10),
      activeShape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(24)

      ),
    );
  }
}


Happy Coding :)
...........................................................................................................................................................................................................................
Example :#2 [ Slider ]

https://pub.dev/packages/carousel_pro/install
  carousel_pro: ^1.0.0




Happy Coding :)
...........................................................................................................................................................................................................................
Example :#3 []

Happy Coding :)

Saturday, December 12, 2020

Banner | Chip | Expansion

 ...................................................................................................................................................................................................................................
Example :#1 [ Banner ]

import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainScreen(),
     // getPages: Router.route,
      //initialRoute: '/login',
    );
  }
}


class MainScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.deepPurple,
        title: Text('AbodeXD to Flutter'),
      ),
      body: Container(
        padding: EdgeInsets.all(16),
        child: Align(
          alignment: Alignment.topCenter,
          child: Banner(
            message: 'Offer 20% off',
            location: BannerLocation.topEnd,
            color: Colors.red,
            child: Container(
              height: 200,
              width: 200,
              child: Image.network(
                'https://upload.wikimedia.org/wikipedia/commons/6/6d/Good_Food_Display_-_NCI_Visuals_Online.jpg',
                fit: BoxFit.fill,
              ),
            ),
          ),
        ),
      ),
    );
  }
}



Happy Coding :)
 ...................................................................................................................................................................................................................................
Example :#2 []


Happy Coding :)
 ...................................................................................................................................................................................................................................
Example :#3 []


Happy Coding :)
 ...................................................................................................................................................................................................................................
Example :#4 []
Happy Coding :)

Sunday, December 6, 2020

GetX

 Installation
Add Get to your pubspec.yaml file:
  get: ^3.22.2
https://pub.dev/packages/get/install

Import get in files that will be used.
import 'package:get/get.dart';

Tips: #1


...............................................................................................................................................................................................................................
Example :#1[]

import 'package:flutter/material.dart';
import 'package:get/get.dart';

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

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

class Home extends StatelessWidget {
  final CounterController controller = Get.put(CounterController());
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hello'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => controller.increment(),
      ),
      body: Center(
        child: Obx(() => Text( '${controller.count}', )),
      ),
    );
  }
}

class CounterController extends GetxController {
  var count = 0.obs;
  void increment() => count++;
}






Happy Coding :)
...............................................................................................................................................................................................................................
Example :#2[]





Happy Coding :)
...............................................................................................................................................................................................................................
Example :#3[ ]

import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

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

class _HomeState extends State<Home> {
  Counter counter = Get.put(Counter());

  int co;

  @override
  void initState() {
    super.initState();
    counter.startStream();
  }

  void AddData() {
    Map<String, int> demodate = {
      "count": (co + 1).toInt(),
    };
    DocumentReference documentReference =
        FirebaseFirestore.instance.collection('data').doc('counterState');
    documentReference.update(demodate);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () => AddData(),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(
              child: StreamBuilder(
                //stream: counter.streamController.stream,
                stream: counter.streamController.stream,

                builder: (context, snapshot) {
                  co = snapshot.data;
                  return Text('Data: $co');
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

class Counter extends GetxController {
  StreamController<int> streamController = StreamController<int>();
  
  Stream<DocumentSnapshot> pathStream = FirebaseFirestore.instance
      .collection('data')
      .doc('counterState')
      .snapshots();

  void startStream() {
    pathStream.listen((event) {
      streamController.sink.add(event.data()['count']);
    });
  }

  @override
  void onClose() {
    streamController.close();
  }
}
....................
import 'package:flutter/material.dart';
import 'package:getProject/screens/home.dart';
import 'package:get/get.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

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

Happy Coding :)
...............................................................................................................................................................................................................................
Example :#4[]



Happy Coding :)

Friday, November 27, 2020

Biometric |Qr Code Scanner | OCR Reader | Text Scanner

.................................................................................................................................................................................................................................. 
Example  :#1 [ Biometric ]

Setup

Update the project's AndroidManifest.xml file to include the USE_FINGERPRINT permissions:

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

FlutterFragmentActivity as opposed to FlutterActivity in the java or kt




Library
https://pub.dev/packages/local_auth/install
  local_auth: ^0.6.3+4

...........................................................................................................................................................................................................................................
Example :#1[Biometric ]
1.Code Here

Home.dart

import 'package:demo/auth.dart';
import 'package:flutter/material.dart';

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

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
        actions: [
          IconButton(
              icon: Icon(Icons.exit_to_app),
              iconSize: 20,
              onPressed: () {
                Navigator.pushReplacement(context, MaterialPageRoute(
                  builder: (context) => Auth()
                  
                ));
              })
        ],
      ),
    );
  }
}
......................
Auth.dart

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

class Auth extends StatefulWidget {
  @override
  _AuthState createState() => _AuthState();
}

class _AuthState extends State<Auth> {
  LocalAuthentication localAuthentication = LocalAuthentication();
  bool _checkBio = false;
  bool _isBioFinger = false;

  @override
  void initState() {
    super.initState();
    _checkBioMetric();
    _listBioAndFindFingerType();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Auth'),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              IconButton(
                  icon: Icon(
                    Icons.fingerprint,
                  ),
                  iconSize: 100,
                  onPressed: startAuth)
            ],
          ),
        ),
      ),
    );
  }

  void _checkBioMetric() async {
    try {
      final bio = await localAuthentication.canCheckBiometrics;
      setState(() {
        _checkBio = bio;
      });
      print(' BioMetric = $_checkBio');
    } catch (e) {}
  }

  void _listBioAndFindFingerType() async {
    List<BiometricType> listType;

    try {
      listType = await localAuthentication.getAvailableBiometrics();
    } on PlatformException catch (e) {
      print(e.message);
    }
    print('list =$listType');
    if (listType.contains(BiometricType.fingerprint)) {
      setState(() {
        _isBioFinger = true;
      });
      print('FingerPrint is $_isBioFinger');
    }
  }

  void startAuth() async {
    bool _isAuthenticated =false;
    try {
      _isAuthenticated = await localAuthentication.authenticateWithBiometrics(
        localizedReason: 'Scan your fingerprint',
        useErrorDialogs: true,
        stickyAuth: true,
        // androidAuthStrings: null,
        // iOSAuthStrings: null
      );
    } on PlatformException catch (e) {
      print(e.message);
    }
    if (_isAuthenticated) {
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (c) => Home()));
    }
  }
}

...............................
main.dart
import 'package:demo/auth.dart';
import 'package:flutter/material.dart';


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

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






2.


3.


4.

5.
6.


7.


8.


9.
10.



11.




Test


...........................................................................................................................................................................................................................................
Example :#1.2 [ Fingerprint / Face unlock local authentication using flutter]

import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';

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> {
  LocalAuthentication localAuthentication = LocalAuthentication();
  bool canAuth = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Local Auth'),
      ),
      body: Center(
        child: Column(
          children: [
            RaisedButton(
                child: Text('Check'),
                onPressed: () async {
                  canAuth = await localAuthentication.canCheckBiometrics;
                  print(canAuth.toString());
                }),
            RaisedButton(
                child: Text('Verify'),
                onPressed: () async {
                  List<BiometricType> list = List();
                  try {
                    if (canAuth) {
                      list = await localAuthentication.getAvailableBiometrics();
                      if (list.length > 0) {
                        bool result =
                            await localAuthentication.authenticateWithBiometrics(
                                localizedReason:
                                    'Please Enter your FingerPrint to unlock',
                                useErrorDialogs: true,
                                stickyAuth: true);
                        print('result is ${result}');
                        if (list.contains(BiometricType.fingerprint)) {
                          print('Fingerprint');
                        }
                        if (list.contains(BiometricType.iris)) {
                          print('iris');
                        }
                        if (list.contains(BiometricType.face)) {
                          print('Face unlock');
                        }
                      }
                    }
                  } catch (e) {}
                })
          ],
        ),
      ),
    );
  }
}


Happy Coding :)
...........................................................................................................................................................................................................................................
Example :#2 [Qr Code Scanner]

Library
https://pub.dev/packages/qr_code_scanner/install
  qr_code_scanner: ^0.0.13

min 24
..............................
Code Here






Happy Coding :)
...........................................................................................................................................................................................................................................
Example :#3[ Flutter: OCR Reader | Text Scanner]

Library
https://pub.dev/packages/flutter_mobile_vision
  flutter_mobile_vision: ^0.1.4+1
.............................
AndroidManifest.xml

         <uses-permission android:name="android.permission.CAMERA" />
         <uses-feature android:name="android.hardware.camera" />

<activity android:name="io.github.edufolly.fluttermobilevision.barcode.BarcodeCaptureActivity" />

..............................
Code Here
import 'package:flutter/material.dart';
import 'package:flutter_mobile_vision/flutter_mobile_vision.dart';

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> {
  bool isInitilized = false;
  @override
  void initState() {
    FlutterMobileVision.start().then((value) {
      isInitilized = true;
    });
    super.initState();
  }

  _startScan() async {
    List<OcrText> list = List();
    try {
      FlutterMobileVision.read(
        waitTap: true,
        fps: 5,
        multiple: true
      );
      for(OcrText text in list){
        print('value is ${text.value}');
      }
    } catch (e) {}
  }

  @override

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('OCR Reader | Text Scanner App'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.camera_alt),
        onPressed:()=> _startScan(),
      ),
    );
  }
}

Happy Coding :)
...........................................................................................................................................................................................................................................
Example :#4


Thursday, November 26, 2020

Payment | Razorpay | paytm | more

Razorpay Flutter
Setup






..........................

Library
razorpay_flutter: ^1.2.2
https://pub.dev/packages/razorpay_flutter/install 
....................................................................................................................................................................................................................................
Example :#1[ Razorpay ]

import 'package:flutter/material.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';

class Payment extends StatefulWidget {
  @override
  _PaymentState createState() => _PaymentState();
}

class _PaymentState extends State<Payment> {
  TextEditingController controller = TextEditingController();

  final razorpay = Razorpay();
  @override
  void initState() {
    razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, externalwallet);
    razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, paymentSuccess);
    razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, paymentError);
    super.initState();
  }

  void externalwallet(ExternalWalletResponse response) {
    print(response.walletName);
  }

  void paymentSuccess(PaymentSuccessResponse response) {
    print(response.paymentId.toString());
  }

  void paymentError(PaymentFailureResponse response) {
    print(response.message + response.code.toString());
  }



  getPayment() {
    var options = {
      'key': 'rzp_test_kQTbnMutkQcGQk',
      'amount': double.parse(controller.text.trim()) * 100,
     // 'order': '${controller.text.trim()}Sapan',
      'name': 'Sapan'
    };
    try {
      razorpay.open(options);
    } catch (e) {
      print('$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Razorpay'),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            children: [
              TextField(
                controller: controller,
                keyboardType: TextInputType.number,
              ),
              RaisedButton(
                  child: Text('Pay'),
                  onPressed: () {
                    getPayment();
                  })
            ],
          ),
        ),
      ),
    );
  }
}
CVV is 123










Happy Coding :)
 ....................................................................................................................................................................................................................................
Example :#2



 ....................................................................................................................................................................................................................................
Example :#3


 ....................................................................................................................................................................................................................................
Example :#4


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 :)










Sunday, November 22, 2020

DateTime picker in flutter

...............................................................................................................................................................................................................................
Example : #1 [ Datepicker and time picker ]

import 'package:flutter/material.dart';

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> {
  DateTime _dateTime;
  TimeOfDay _timeOfDay;


  Future<void> gettime() async {
    TimeOfDay timeOfDay = await showTimePicker(
        context: context,
        initialTime: TimeOfDay(
            hour: TimeOfDay.now().hour, minute: TimeOfDay.now().minute));
    setState(() {
      _timeOfDay = timeOfDay;
    });
  }


  Future<void> getdate() async {
    DateTime datetime = await showDatePicker(
        context: context,
        initialDate: DateTime(DateTime.now().year),
        firstDate: DateTime(DateTime.now().year - 20),
        lastDate: DateTime(DateTime.now().year + 2));
    setState(() {
      _dateTime = datetime;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Alert'),
        ),
        body: Center(
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
            _dateTime == null
                ? Text('Choose Date')
                : Text(
                    '${_dateTime.year}, ${_dateTime.month}, ${_dateTime.day}'),

            _timeOfDay == null
                ? Text('Choose time')
                : Text('${_timeOfDay.hour},${_timeOfDay.minute}'),

            RaisedButton(
                child: Text('Date Picker'),
                onPressed: () {
                  getdate();
                }),
            RaisedButton(
                child: Text('Show time Picker'),
                onPressed: () {
                  gettime();
                })
          ]),
        ));
  }
}


ModalBottomSheet || Alert || SnackBar | Custom Dialog

  1. showModalBottomSheet 
  2. AlertDialog
  3. Custom Dialog
  4. Snackbar
...........................................................................................................................................................................................................................
Example : #1 [ showModalBottomSheet ]
import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Bottom(),
    );
  }
}
class Bottom extends StatefulWidget {
  @override
  _BottomState createState() => _BottomState();
}
class _BottomState extends State<Bottom> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bottom Sheet'),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            children: [
              RaisedButton(onPressed: () {
                _bottoSheet(context);
              })
            ],
          ),
        ),
      ),
    );
  }
  _bottoSheet(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Wrap(
            children: [
              Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Login"),
                    Text("Login"),
                    Text("Login"),
                    Divider(
                      height: 2.0,
                    ),
                    Text("Login"),
                    Text("Login"),
                    Text("Login"),
                  ],
                ),
              ),
            ],
          );
        });
  }
}

...........................................................................................................................................................................................................................
Example : #2 [ AlertDialog]

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

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

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Alert'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(onPressed: () {
              _alert(context);
            })
          ],
        ),
      ),
    );
  }

  _alert(BuildContext context) {
    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('Alert'),
          content: Text('Write Something Message Here'),
          actions: [
            RaisedButton(
                child: Text('Okay'),
                onPressed: () {
                  Navigator.of(context).pop();
                })
          ],
        );
      },
    );
  }
}



...........................................................................................................................................................................................................................
Example : #3 [ showSnackbar  ]
  • Global Key
import 'package:flutter/material.dart';

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

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

class Home extends StatelessWidget {
  GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _globalKey,
      appBar: AppBar(
        title: Text('SnackBar'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Login'),
          onPressed: () {
            _globalKey.currentState.showSnackBar(SnackBar(
              content: Text('Iam Snack Bar'),
              duration: Duration(seconds: 3),
              ));
          },
        ),
      ),
    );
  }
}
Happy Coding :)
...........................................................................................................................................................................................................................
Example : #4 [ Snackbar ]
  • Split a build function
import 'package:flutter/material.dart';

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

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

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SnackBar'),
      ),
      body: Snackbarpage(),
    );
  }
}

class Snackbarpage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: RaisedButton(
        child: Text('Login'),
        onPressed: () {
          SnackBar snackBar = SnackBar(
            content: Text('I am Snack Bar'),
            duration: Duration(seconds: 3),
            action: SnackBarAction(
              label: 'Undo',
              onPressed: () {},
            ),
          );
          Scaffold.of(context).showSnackBar(snackBar);
        },
      ),
    );
  }
}
Happy Coding :)
...........................................................................................................................................................................................................................
Example : #5 [ Snackbar ]
Builder Widget
import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

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

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SnackBar'),
      ),
      body: Column(
        children: [
          Builder(
            builder: (context) {
              return RaisedButton(onPressed: () {
                Scaffold.of(context).showSnackBar(SnackBar(
                  content: Text('Show Snack Bar..'),
                  duration: Duration(seconds: 3),
                  ));
              });
            },
          ),
        ],
      ),
    );
  }
}
Happy Coding :)
...........................................................................................................................................................................................................................
Example : #6 [ Dialog]
import 'package:flutter/material.dart';
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> {
  void showSimpleDialog(BuildContext context) =>showDialog(
      context: context,
      child: SimpleDialog(
        title: Text('Simple options'),
        children: [
          SimpleDialogOption(
            padding: EdgeInsets.symmetric(horizontal: 25, vertical: 25),
            child: Text('Option 1'),
          ),
          SimpleDialogOption(
            child: Text('Option 1'),
          ),
        ],
      ),
    );
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text('Dialog'),
        ),
        body: Center(
          child: Column(
            children: [
              RaisedButton(
                  child: Text('Simple Dialog'),
                  color: Colors.deepOrange,
                  onPressed: () => showSimpleDialog(context))
            ],
          ),
        ));
  }
}
Happy Coding :)
...........................................................................................................................................................................................................................
Example : #7 [ showModalBottomSheet ]




...........................................................................................................................................................................................................................
Example : #8 [ showModalBottomSheet ]



...........................................................................................................................................................................................................................
Example : #9 [ showModalBottomSheet ]