Home Blog Page 62

GetX Flutter check internet connection – Connectivity – State Management

0

Hi Guys, Welcome to Proto Coders Point.

In this Flutter tutorial(Article) we will learn how to check internet connection continuously in flutter by using flutter connectivity package & implement network change state management using Flutter GetX package.

About flutter connectivity package

This plugin is very useful if your app need internet connection to run the application perfectly, This Library allows your flutter Application to Discover Network Connectivity. This Flutter Library will also check if your  mobile is currently using cellular mobile data  or is using WiFi Connection.

This Flutter Plugin Perfectly works for Both Android and iOS devices, So it is been rated with 100 points in Flutter Library Store.

Video Tutorial


Flutter check internet connection using Connectivity and GetX State management package

Project Files Structure of references

Note: In File Structure, ‘generated_plugin_registrant.dart’ get automatically created when you add below dependencies. You no need to create it.

1. Add Dependencies

dependencies:
  get:
  connectivity:

As we know, we need 2 packages i.e. Flutter GetX and Flutter connectivity.

Flutter GetX: To implement State Management, suppose if Internet Connection changed, to update the state of app and tell about the network change by updating UI screen of users.

Flutter Connectivity: This package plugin helps to check connectivity, if you are connected to WIFI or Mobile Data or if flutter no internet connection. Note: Connectivity plugin has stopped further updated, so Kindly use Connectivity_plus. Don’t worry code is same as it is in Connectivity plugin.

2. GetX State management- flutter check internet connection

Now, Create a dart file in lib directory of your flutter project.

I have created the file and named it as ‘GetXNetworkManager.dart’

GetXNetworkManager.dart

This Class manager all the network related task such as checkConnectivity, ConnectivityResult weather your mobile is connected to WIFI, Mobile Data, or no Internet connection.

import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

class GetXNetworkManager extends GetxController
{
   //this variable 0 = No Internet, 1 = connected to WIFI ,2 = connected to Mobile Data.
   int connectionType = 0;

   //Instance of Flutter Connectivity
   final Connectivity _connectivity = Connectivity();

   //Stream to keep listening to network change state
   late StreamSubscription _streamSubscription ;

  @override
  void onInit() {
     GetConnectionType();
     _streamSubscription = _connectivity.onConnectivityChanged.listen(_updateState);
  }

  // a method to get which connection result, if you we connected to internet or no if yes then which network
   Future<void>GetConnectionType() async{
    var connectivityResult;
    try{
      connectivityResult = await (_connectivity.checkConnectivity());
    }on PlatformException catch(e){
      print(e);
    }
    return _updateState(connectivityResult);
   }

   // state update, of network, if you are connected to WIFI connectionType will get set to 1,
   // and update the state to the consumer of that variable.
   _updateState(ConnectivityResult result)
   {
     switch(result)
     {
       case ConnectivityResult.wifi:
               connectionType=1;
               update();
               break;
       case ConnectivityResult.mobile:
         connectionType=2;
         update();
         break;
       case ConnectivityResult.none:
         connectionType=0;
         update();
         break;
       default: Get.snackbar('Network Error', 'Failed to get Network Status');
       break;

     }
   }

  @override
  void onClose() {
    //stop listening to network state when app is closed
     _streamSubscription.cancel();
  }
}

3. Getx initial Binding

Now, create one more dart file for bindings between GetXNetworkManager.dart and main.dart.

I have create it and named it as ‘NetworkBinding.dart’

This dart file, class extends Bindings & must have a @override method i.e. Dependenies(), which will then load our GetXNetworkManager class by using Get.LazyPut().

import 'package:get/get.dart';
import 'package:getx_check_internet/GetxNetworkManager.dart';

class NetworkBinding extends Bindings{

  // dependence injection attach our class.
  @override
  void dependencies() {
    // TODO: implement dependencies
    Get.lazyPut<GetXNetworkManager>(() => GetXNetworkManager());
  }

}

4. main.dart file

In main.dart file , instead of simple MaterialApp, we are using GetMaterialApp, inside it we are using a property called as initialBinding that then invoke GetXNetworkManager class.

Then in stateful widget, we create an Instance of GetXNetworkManager(GetXController) class so that we can use properties of GetXNetworkManager from main.dart.

main.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_check_internet/GetxNetworkManager.dart';
import 'package:getx_check_internet/NetworkBinding.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      //Initiate Bindings we have created with GETX
      initialBinding: NetworkBinding() ,
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {

  // create an instance
  final GetXNetworkManager _networkManager = Get.find<GetXNetworkManager>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Network Status',style: TextStyle(fontSize: 20),),
            //update the Network State
            GetBuilder<GetXNetworkManager>(builder: (builder)=>Text((_networkManager.connectionType == 0 )? 'No Internet' : (_networkManager.connectionType == 1) ? 'You are Connected to Wifi' : 'You are Connected to Mobile Internet',style: TextStyle(fontSize: 30),)),

          ],
        ),
      ),
    );
  }
}


Output


Palindrome program in dart – Check if Number, String is palindrome or not

0
palindrome program in dart
palindrome program in dart

Hi Guys, Welcome to Proto Coders Point.

In this dart programming article, we will learn what is a palindrome, A dart Programs on “how to check if a number is palindrome”, “check if string is palindrome or not”.

What is a Palindrome – number, string

Palindrome meaning(defination), A Number or a string when reversed looks same and pronounced same as it was before reversing.

For Example: 656 when reversed will be same, ( it’s a palindome number), 657 when reversed is 756 so ( it’s not a palindrome number). like wise 252,25252,49694.

String Example for palindrome: NITIN, MADAM, ABBA, MAM, STRAW WARTS, DAMMIT IM MAD.

Palindrome Number algorithm – Code Work flow

  1. Get a number to check if palindrome or not.
  2. Store the same number, in temp variable.
  3. Reverse number using mathematical operation or string methods.
  4. Now compare temp variable with the reversed number value.
  5. If both number match ‘Then it’s a palindrome number’
  6. Else ‘Not a Palindrome Number’

Now Let’s see a palindrome number program in dart language.

void main(){
  int reminder, sum =0, temp;
  int number = 54545;

  temp = number;

  // a loop to reverse a number
  while(number>0)
  {
    reminder = number % 10;  //get remainder
    sum = (sum*10)+reminder;
    number = number~/10;
  }
  
  if(sum == temp)
  {
    print('Its A Palindrome number');

  }else{
    print('Its A Not Palindrome number');
  }


 // StringNumber();
}
palindrome number output
not a palindrome number

Palindrome program in dart programming language (Another way)

Here in below dart program, A user can input either a number or string to check for palindrome or not.

Here we are accepting a input from a user and then reverse the string and then matching them.

How to reverse a string in dart

stringValue!.split('').reversed.join('')
import 'dart:io';
void main(){
print('Enter Words or number');
    // User enter a string or a number
    String? original =  stdin.readLineSync();
  
   // then we will reverse the input
   String? reverse = original!.split('').reversed.join('');

  // then we will compare
  if(original == reverse)
  {
    print('Its A Palindrome');

  }else{
    print('Its A Not Palindrome');
  }
 
}
check is given input is palindrome or not a palindrome

Recommended dart basic programs

Generate random number in dart

String to ASCII in dart

Pattern Program in dart

Fibonacci program in dart

prime number program in dart

Learn dart basic programs

How to make a Count Down Timer in flutter dart

0
flutter count down timer
count down timer in flutter

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, we will implement a count down timer in flutter application using Timer Class of dart language.

Note: In this tutorial, we will cover 2 ways to implement count down timer flutter.

  1. Count-down timer using setState() to update Timer Value.
  2. Count-down timer using Getx StateManagement to update Timer Value.

If you are android developer, I have written a tutorial with source code for implementing count down timer in android app.

How we will use Timer Class in flutter

We are going to make use of dart Timer Class with periodic function to implement CountDownTimer. A Timer Class can we used to make count down in flutter app.

use a periodic timer to repeatedly loop in same interval time. Inside Timer.periodic set a fixed interval duration so that a loop runs exactly at a duration as defined.

Example: Snippet code

Timer _timer = Timer.periodic(Duration(seconds: 1), (timer) {
       
   // The Inner Block works Exactly after every 1 second as defined.
   
   // You can perform  variable count down here

   // Important, you need to Stop the Timer loop when you want to end it Eg: when value = 0
   _timer.cancel(); // will stop it

    });


1. Implementation of Count Down Timer using setState to update the Timer Value

Video Tutorial

main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_timer/ByGetXStatemanagement.dart';
import 'package:flutter_timer/BySetState.dart';
import 'package:flutter_timer/CountDownTimerState.dart';
import 'package:get/get.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                onPressed: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (build) => BySetState()));
                },
                child: Text('Count Down Timer using setState ();')),
            SizedBox(
              height: 30,
            ),
            ElevatedButton(
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (build) => ByGetXStateManagement()));
                },
                child: Text('Count Down Timer using GetX StateManagement')),
          ],
        ),
      ),
    );
  }
}

BySetState.dart

import 'dart:async';

import 'package:flutter/material.dart';

class BySetState extends StatefulWidget {
  @override
  _BySetStateState createState() => _BySetStateState();
}

class _BySetStateState extends State<BySetState> {
  int _counter = 10;
  late Timer _timer;

  void _startTimer() {
    _counter = 10;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_counter > 0) {
        setState(() {
          _counter--;
        });
      } else {
        _timer.cancel();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Count Down Timer using SetState to keep updating'),
            SizedBox(
              height: 20,
            ),
            Text(
              '$_counter',
              style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
            ),
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                onPressed: () {
                  _startTimer();
                },
                child: Text('Start Timer')),
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                onPressed: () {
                  _timer.cancel();
                },
                child: Text('Pause')),
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    _timer.cancel();
                    _counter = 10;
                  });
                },
                child: Text('Reset'))
          ],
        ),
      ),
    );
  }
}
count down timer gif


2. Implementing Count down timer using GetX StateManagement to update Timer Value

Video Tutorial (GetX State Management Example by implementing Count Down Timer)

#Soon

Create a Statemanagement dart class ‘CountDownTimerState.dart’.

CountDownTimerState.dart

import 'dart:async';
import 'package:get/get.dart';

class CountDownTimerState extends GetxController{
  // Initial Count Timer value
  
  var SCount = 10;
  
  //object for Timer Class
  late Timer _timer;

  // a Method to start the Count Down
  void StateTimerStart(){
     //Timer Loop will execute every 1 second, until it reach 0
    // once counter value become 0, we store the timer using _timer.cancel()
    
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {

      if(SCount > 0){
        SCount--;
        update();
      }else{
        _timer.cancel();
      }
    });
  }

  // user can set count down seconds, from TextField
  void setnumber(var num){

        SCount = int.parse(num);
        update();

  }

  // pause the timer
  void Pause(){
    _timer.cancel();
    update();
  }

  // reset count value to 10
  void reset(){
    _timer.cancel();
    SCount = 10 ;
    update();
  }

}

ByGetXStatemanagement.dart

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

class ByGetXStateManagement extends StatefulWidget {
  @override
  _ByGetXStateManagementState createState() => _ByGetXStateManagementState();
}

class _ByGetXStateManagementState extends State<ByGetXStateManagement> {
  final CountDownTimerState TimerState = Get.put(CountDownTimerState());

  final _textEditingController = TextEditingController();

  @override
  void initState() {
    _textEditingController
        .addListener(() => TimerState.setnumber(_textEditingController.text));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Count Down Timer using GetX State management'),
            SizedBox(
                height: 40,
                width: 130,
                child: TextField(
                  controller: _textEditingController,
                  minLines: 1,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(10)))),
                )),
            GetBuilder<CountDownTimerState>(
                builder: (_) => Text('${TimerState.SCount}')),
            ElevatedButton(
                onPressed: () {
                  TimerState.StateTimerStart();
                },
                child: Text('Start Getx State Timer')),
            SizedBox(
              height: 20,
            ),
            ElevatedButton(
              onPressed: () {
                TimerState.Pause();
              },
              child: Text('Pause'),
            ),
            SizedBox(
              height: 20,
            ),
            ElevatedButton(
              onPressed: () {
                TimerState.reset();
              },
              child: Text('Reset'),
            ),
          ],
        ),
      ),
    );
  }
}

Recommended Flutter Tutorial Articles

Learn State Management

Flutter Provider – State management

Basic of GetX package

Dark & Light Theme using GETX

How to generate random number in dart program

0
how to generate random number in dart
generate random number in dart

Hi Guys, Welcome to Proto Coders Point.

In this dart tutorial (article), we will learn how to generate random number in dart.

In Dart programming, A Random number are often used in flutter application where a user can generate a unique key number.

What is Random Number in dart program?

In dart, A Random Number is a randomly generated from a large set of numbers & select a number using some mathematical algorithm.

Generating random number are commonly implemented in many flutter application having a feature like OTP verification for user SignIn.

One of the best example where dart random number in range is implemented is dice game, whenever a dice is thrown we get a fixed range of random number ranging between 1 – 6.

Dart Random class – In math package

In dart, we have a class named “Random” which is used to generate random integer number, bool , random decimal number.

Note: To use Random class in dart, we must import ‘dart:math’ packagem because Random Class is defined in dart:math package.

It can generate random booleon, integer and double value by using its method provided.

Method on Math.random class

MethodDescription
nextBool() =>Generate either true or false randomly.
nextDouble() => Generate an positive floating point number ranging from 0.0 to 1.0.
nextInt(int max) => Generate a positive number range from 0 to max(as defined)
Eg: random.nextInt(6); // Here 6 is a range, number will generate from 0 – 6.

Dart Porgram to generate random number bool, int, double

1. Dart Program random number

import 'dart:math';

void main() {
  var random = new Random();

   print(random.nextBool()); //true or false

   print(random.nextInt(75)); // number between 0 - 75

   print(random.nextDouble());  // double value 0.0 to 1.0

}
dart random number output

2. How to generate fixed digit number

Eg: Generate a fixed 5 digit or 6 digit random number.

import 'dart:math';

void main() {
   Generate5digit();
}

Generate5digit(){
     var rng = new Random();
     var rand = rng.nextInt(90000) + 10000;
     print(rand.toInt());
}

So in above dart code, you can get a random number in range 00000 to 90000 and add 10000 to it. you always get a 5 digit random number generated.

5 digit random number dart

3. How to get dart random number between range. Eg : 50 – 100

import 'dart:math';

void main() {
  var random = new Random();
  print(''); //just for next line space in output

  print(' Random Number from 0 - 50 :  ${next(0, 50,random)}');

  print('');
}


int next(int min, int max,Random rand) => min + rand.nextInt(max - min);
dart random number between range


How to Generate OTP number in flutter

Flutter Multi-Line TextFormField

0
flutter texrfield with multi line
flutter texrfield with multi line

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Tutorial we will learn how to implement a text field with multiline input supported.
Means a user can input more then one line in textfield.

By Default, a TextFormField widget is set to single line input, but some time a user might want to Enter lines of Text message in the textfield & the TextField size must got extending as the user enter the text.

Allow textFormField with multiple lines input

So to make a TextField accept multiple lines, simply make use of maxLines property in TextField or TextFormField widget.

And keyboardType property set it to TextInputType.multiline, so that user will get a button using which he/she can move the cursor to next line.

Eg:

TextField

TextField(
              minLines: 1,
              maxLines: 5,  // allow user to enter 5 line in textfield
              keyboardType: TextInputType.multiline,  // user keyboard will have a button to move cursor to next line
              controller: _Textcontroller,
            ),

TextFormField

TextFormField(
              minLines: 1,
              maxLines: 5,  // allow user to enter 5 line in textfield
              keyboardType: TextInputType.multiline,  // user keyboard will have a button to move cursor to next line
              controller: _Textcontroller,
            ),

Complete Source – Multiline input textfield flutter- TextEditingController

Here is Complete Source code, Flutter Multline TextField and TextEditingController to handle text that is been entered by user.

Video Tutorial


main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:read_json_file/MutltTextFieldline.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MultiLineTextField(), // call page to display
    );
  }
}

MultiLineTextField.dart

import 'package:flutter/material.dart';

class MultiLineTextField extends StatefulWidget {
  @override
  _MultiLineTextFieldState createState() => _MultiLineTextFieldState();
}

class _MultiLineTextFieldState extends State<MultiLineTextField> {
  // text controller to handle user entered data in textfield
  final TextEditingController _Textcontroller = TextEditingController();
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
           (_Textcontroller.value.text.isEmpty) ? Text("Please Enter Message") :Text('Sent Message: ${_Textcontroller.value.text}'),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: TextFormField(
                controller: _Textcontroller,
                minLines: 2,
                maxLines: 5,
                keyboardType: TextInputType.multiline,
                decoration: InputDecoration(
                  hintText: 'Enter A Message Here',
                  hintStyle: TextStyle(
                    color: Colors.grey
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(10)),
                  )
                ),
              ),
            ),
            TextFormField(
              minLines: 1,
              maxLines: 5,  // allow user to enter 5 line in textfield
              keyboardType: TextInputType.multiline,  // user keyboard will have a button to move cursor to next line
              controller: _Textcontroller,
            ),
            ElevatedButton(onPressed: (){
              setState(() {
                _Textcontroller.notifyListeners();
              });
            },child: Text("Send Message"),)
          ],
        ),
      ),
    );
  }
}

How to read json file in flutter & display in listview

0
Read json file in flutter and show the data in flutter listview.
Read json file in flutter and show the data in flutter listview.

Hi Guys, Welcome to Proto Coders Point.

In this Flutter tutorial(Article), We will learn how to read json file in flutter & parse local JSON file in flutter & the Display the JSON file data in flutter listview builder.

Final Output

read json file display listviewflutter

Video Tutorial – Example on reading json file, parse json data or fetch json data in flutter

You can watch the above video or continue reading…

So Let’s begin

Implementing flutter read local JSON file from assets folder.

1. Create a new flutter project

Firstly, need to create a new flutter project or simply only any existing flutter project where you want to implement read local JSON file in flutter.

In my case, I make use of android stdio to develop flutter application.

creating new flutter project:
File > New > New Flutter Project.

Give a good name & package name to project and finish.
Done your flutter project is ready.

2. How to add JSON file in flutter project

I have created a JSON file by name ProductItem.json which has a list of 10 shoes products (id, name, category, imageUrl, oldPrice & price of each item).

you can download the json file from below button or simply create you own json file.

Create a directory under flutter project & paste the ProductItem.json file in the directory.

3. Create a data model class file

ProductDataModel.dart is used to handle our data that is been used to read from JSON file.

This class has dataTypes & constructor & a method.

ProductDataModel.fromJson is used to assign the data to variable in MAP json format.

Check out this Post Flutter Auto Create Model from JSON File

ProductDataModel.dart

class ProductDataModel{
  //data Type
  int? id;
  String? name;
  String? category;
  String? imageURL;
  String? oldPrice;
  String? price;

// constructor
  ProductDataModel(
      {
       this.id,
      this.name,
      this.category,
      this.imageURL,
      this.oldPrice,
      this.price
      }
   );

  //method that assign values to respective datatype vairables
  ProductDataModel.fromJson(Map<String,dynamic> json)
  {
    id = json['id'];
    name =json['name'];
    category = json['category'];
    imageURL = json['imageUrl'];
    oldPrice = json['oldPrice'];
    price = json['price'];
  }
}

4. Reading JSON file & display the data in listview

Explanition of what is done in main.dart file.

1. Import services.dart as rootBundle

import 'package:flutter/services.dart' as rootBundle;

This will help us in reading json file.

2. Create Method to read json file in flutter

Future<List<ProductDataModel>> ReadJsonData() async {
    //read json file
    final jsondata = await rootBundle.rootBundle.loadString('jsonfile/productlist.json');
    //decode json data as list
    final list = json.decode(jsondata) as List<dynamic>;
    
    //map json and initialize using DataModel
    return list.map((e) => ProductDataModel.fromJson(e)).toList();
  }

3. FutureBuilder to parse & display data in listview

 FutureBuilder(
      future: ReadJsonData(),
      builder: (context, data) {
        if (data.hasError) {
         //in case if error found
          return Center(child: Text("${data.error}"));
        } else if (data.hasData) {
           //once data is ready this else block will execute
          // items will hold all the data of DataModel
           //items[index].name can be used to fetch name of product as done below
          var items = data.data as List<ProductDataModel>;
          return ListView.builder(
              itemCount: items == null ? 0 : items.length,
              itemBuilder: (context, index) {
                return Card(
                  elevation: 5,
                  margin: EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                  child: Container(
                    padding: EdgeInsets.all(8),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 50,
                          height: 50,
                          child: Image(
                            image:
                                NetworkImage(items[index].imageURL.toString()),
                            fit: BoxFit.fill,
                          ),
                        ),
                        Expanded(
                            child: Container(
                          padding: EdgeInsets.only(bottom: 8),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Padding(
                                padding: EdgeInsets.only(left: 8, right: 8),
                                child: Text(
                                  items[index].name.toString(),
                                  style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 8, right: 8),
                                child: Text(items[index].price.toString()),
                              )
                            ],
                          ),
                        ))
                      ],
                    ),
                  ),
                );
              });
        } else {
              // show circular progress while data is getting fetched from json file
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    )

Complete Code – Read JSON file in flutter & display data on screen using ListView.Builder

main.dart

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:read_json_file/ProductDataModel.dart';
import 'package:flutter/services.dart' as rootBundle;

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: FutureBuilder(
      future: ReadJsonData(),
      builder: (context, data) {
        if (data.hasError) {
          return Center(child: Text("${data.error}"));
        } else if (data.hasData) {
          var items = data.data as List<ProductDataModel>;
          return ListView.builder(
              itemCount: items == null ? 0 : items.length,
              itemBuilder: (context, index) {
                return Card(
                  elevation: 5,
                  margin: EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                  child: Container(
                    padding: EdgeInsets.all(8),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 50,
                          height: 50,
                          child: Image(
                            image:
                                NetworkImage(items[index].imageURL.toString()),
                            fit: BoxFit.fill,
                          ),
                        ),
                        Expanded(
                            child: Container(
                          padding: EdgeInsets.only(bottom: 8),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Padding(
                                padding: EdgeInsets.only(left: 8, right: 8),
                                child: Text(
                                  items[index].name.toString(),
                                  style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 8, right: 8),
                                child: Text(items[index].price.toString()),
                              )
                            ],
                          ),
                        ))
                      ],
                    ),
                  ),
                );
              });
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    )
    );
  }

  Future<List<ProductDataModel>> ReadJsonData() async {
    final jsondata = await rootBundle.rootBundle.loadString('jsonfile/productlist.json');
    final list = json.decode(jsondata) as List<dynamic>;
    return list.map((e) => ProductDataModel.fromJson(e)).toList();
  }
}

Output