Holte CastHolte Cast
  • Technology
  • News
  • Social Media
  • Investment
  • Fashion
  • Gaming
  • Other
Facebook Twitter Instagram
Tuesday, March 21
Facebook Twitter Instagram
Holte CastHolte Cast
Subscribe
  • Technology
  • News
  • Social Media
  • Investment
  • Fashion
  • Gaming
  • Other
Holte CastHolte Cast
Home»Software»How To Use MVVM in Flutter App Development?
Software

How To Use MVVM in Flutter App Development?

adminBy adminJanuary 19, 2023No Comments7 Mins Read
Facebook Twitter Pinterest LinkedIn Tumblr Email
How To Use MVVM in Flutter App Development?
How To Use MVVM in Flutter App Development?
Share
Facebook Twitter LinkedIn Pinterest Email

Flutter is one of the popular cross-platform frameworks which enable you to create android and ios apps with a single codebase. MVVM stands for Model View ViewModel and is the most effective software architectural pattern. It supports the UI separation from the backend logic and business logo development. 

The Flutter application does not use a certain design pattern, so the developer implements the right pattern that meets their requirements. You can hire a flutter developer from www.flutteragency.com to follow the right process in flutter app development and implement the MVVM effectively. Flutter’s declarative nature makes it a good option for the Model View ViewModel design pattern. Three components control the MVVM, such as Model, View and ViewModel. 

Every component has different responsibilities and functionalities. In addition, it has good interaction between the three components of the app development period. An MVVM design pattern is mostly used in creating Windows Presentation Foundation applications. Keep reading the article to learn simple tips to use MVVM in Flutter!

Components of MVVM

The following are MVVM architecture that every developer must know:

  • Model

The Model in the MVVM is used in the app development that reflects real-time data and not any features regarding the application. 

  • View

MVVM design pattern prevents user interaction with the View. These Flutter libraries provide accurate and reliable data presentation. Besides, View manages the user’s action, which is manipulated by the Model’s functionalities. 

  • ViewModel

ViewModel gets the central position in the MVVM architecture, which sends and receives critical data from the Model. It gives accurate data to the View and detects the data modification. 

In addition, ViewModel shifts data between View and Model in the architecture that recognizes the user request. If the Model has particular data, it returns to ViewModel, and ViewModel informs that record to View.

Guidelines to use MVVM in Flutter

It is easy to implement MVVM in a Flutter app development. If you need to create an application with MVVM architecture, you can follow the below-given steps.  

  • Develop new app 

You should remove all codes if you need to build a new Flutter project. It is because you will insert a custom main.dart.  

  • Obtain dependencies

Add a new version of HTTP and provider in the dependencies. Go to the pubspec.yaml file and add the following items:                                                                  

http: latest 

provider: latest

// use the latest dependencies version from the pub.dev

 

Run “pub get”, and let’s go to the next step.

  • Build the Model

 

If you create the movie search application, the Model will be Movies. You can develop the new folder and give the name of the models in the lib folder. Generate the dark file and name the file as movie.dart within the model folder. Now, you can enter the below-given code:

 

class Movie {

  final String title;

  final String posterUrl;

  Movie({this.title, this.posterUrl});

  factory Movie.fromJson(Map<String, dynamic> json) {

    return Movie(title: json[“Title”], posterUrl: json[“Poster”]);

  }

}

  • Develop the UI

Create a folder named “screens” in your library folder. Name the new file “movies_screen.dart”. Here is the code:

import’ package:flutter/material.dart’;

import ‘package:flutter_app_tutorial/viewModel/movies_list_view_model.dart’;

import ‘package:flutter_app_tutorial/widgets/movies_list.dart’;

import ‘package:provider/provider.dart’;

class MovieListPage extends StatefulWidget {

@override

_MovieListPageState createState() => _MovieListPageState();

}

class _MovieListPageState extends State<MovieListPage> {

final TextEditingController _controller = TextEditingController();

@override

void initState() {

super.initState();

Provider.of<MovieListViewModel>(context, listen: false).fetchMovies(“iron man”);

//Here, the developer can utilize anything they like or do not use.

}

@override

Widget build(BuildContext context) {

final vm = Provider.of<MovieListViewModel>(context);

return Scaffold(

appBar: AppBar(

title: Text(“Movies MVVM Example”)

),

body: Container(

padding: EdgeInsets.all(10),

width: MediaQuery.of(context).size.width,

height: MediaQuery.of(context).size.height,

child: Column(children: <Widget>[

Container(

padding: EdgeInsets.only(left: 10),

decoration: BoxDecoration(

color: Colors.grey,

borderRadius: BorderRadius.circular(10)

),

child: TextField(

controller: _controller,

onSubmitted: (value) {

if(value.isNotEmpty) {

vm.fetchMovies(value);

_controller.clear();

}

},

style: TextStyle(color: Colors.white),

decoration: InputDecoration(

hintText: “Search”,

hintStyle: TextStyle(color: Colors.white),

border: InputBorder.none

),

),

),

Expanded(

child: MovieList(movies: vm.movies))// you will create it in the next step

])

)

);

}

}

  • Build Web Service

You can use the API endpoint to omdbapi.com in the web service. Follow the below-given code:

import ‘dart:convert’;

import ‘package:flutter_app_tutorial/models/movie.dart’;

import’ package:http/http.dart’ as http;

class Webservice {

Future<List<Movie>> fetchMovies(String keyword) async {

final url = “http://www.omdbapi.com/?s=$keyword&apikey=eb0d5538”;

final response = await http.get(url);

if(response.statusCode == 200) {

final body = jsonDecode(response.body);

final Iterable json = body[“Search”];

return json.map((movie) => Movie.fromJson(movie)).toList();

} else {

throw Exception(“Unable to perform request!”);

}

}

}

After pasting this code, you will obtain an error. So, import dart:convert, Model from the movie.dart and package:http/http.dart, which helps fix the error. 

  • Construct the View Model

Please create a new folder and name it viewModel in the lib folder. You can generate two files in this folder. Here are the codes:

import ‘package:flutter_app_tutorial/models/movie.dart’;

class MovieViewModel {

final Movie movie;

MovieViewModel({this.movie});

String get title {

return this.movie.title;

}

String get poster {

return this.movie.posterUrl;

}

}

In the MovieViewModel class, the MovieModel is a factor, and the values it contains are returned from the ViewModel.

The next file is movies_list_view_model, and enter below-given code:

import’ package:flutter/material.dart’;

import ‘package:flutter_app_tutorial/service/web_service.dart’;

import ‘package:flutter_app_tutorial/viewModel/movie_view_model.dart’;

class MovieListViewModel extends ChangeNotifier {

List<MovieViewModel> movies = List<MovieViewModel>();

Future<void> fetchMovies(String keyword) async {

final results = await Webservice().fetchMovies(keyword);

this.movies = results.map((item) => MovieViewModel(movie: item)).toList();

notifyListeners();

}

}

  • Build a Widget

Within a new folder you can create the Flutter widget in the lib folder under the new folder. Inside this folder, create a new file and name it movies_list.dart. Here are coding for building the widget:

import’ package:flutter/material.dart’;

import ‘package:flutter_app_tutorial/viewModel/movie_view_model.dart’;

class MovieList extends StatelessWidget {

final List<MovieViewModel> movies;

MovieList({this.movies});

@override

Widget build(BuildContext context) {

return ListView.builder(

itemCount: this.movies.length,

itemBuilder: (context, index) {

final movie = this.movies[index];

return ListTile(

contentPadding: EdgeInsets.all(10),

leading: Container(

decoration: BoxDecoration(

image: DecorationImage(

fit: BoxFit.cover,

image: NetworkImage(movie.poster)

),

borderRadius: BorderRadius.circular(6)

),

width: 50,

height: 100,

),

title: Text(movie.title),

);

},

);

}

}

ListTile widget is easy, which will display the view model’s data/

  • Develop main.dart

At last, you can build the main.dart file

import’ package:flutter/material.dart’;

import ‘package:flutter_app_tutorial/screens/movies_screen.dart’;

import ‘package:flutter_app_tutorial/viewModel/movies_list_view_model.dart’;

import ‘package:provider/provider.dart’;

void main() => runApp(App());

class App extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: “Movies MVVM Example”,

debugShowCheckedModeBanner: false,

theme: ThemeData(primarySwatch: Colors.teal),

home:

ChangeNotifierProvider(

create: (context) => MovieListViewModel(),

child: MovieListScreen(),

)

);

}

}

 

You can use ChangeNotifierProvider as the parent and create MovieListViewModel() as the child that passes the same screen.

Conclusion

This article is useful for the application developer. It will give you ideas for utilizing MVVM architecture in a flutter. Hire Flutter Experts who give you efficient approaches to the project. You can implement the architecture pattern in mobile app development and enjoy plenty of benefits.

 

I hope that this article was helpful and gave accurate information to you. If you wish to develop the next app in the Flutter framework, then you can connect with one of the top flutter app development companies in the united states for building market leading apps for your business. 

 

Frequently Asked Questions (FAQs)

  • How will MVVM work in Flutter development?

A Flutter MVVM integration will make use of property-based data binding to establish the connection between the ViewModel and View and drive the View changes via a ViewModel.

  • What is the use of MVVM?

MVVM helps to organize the code and separate the programs into modules to make the development, update and reuse of the code quicker and simpler.

  • What is the benefit of using MVVM?

The MVVM pattern will represent the better separation of the concerns by adding the view models to a mix. The view model will translate the data of the model layer into the view layer, which can be 

utilized. Therefore, the controller is not responsible for this task or operation.

Check here

Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
admin
  • Website

Related Posts

5 Best Practices for Keeping Your Device Looking Like New

March 15, 2023

How to Send Form Data Using Axios Post Request In React

March 6, 2023

Top 10 Progressive Web App Development Companies for 2023

March 5, 2023
Add A Comment

Leave A Reply Cancel Reply

Holte Cast
Facebook Twitter Instagram
  • About us
  • Contact us
  • Privacy Policy
© 2023 PerfectSEO. Designed by PerfectSEO.

Type above and press Enter to search. Press Esc to cancel.