More
Building a Sustainable Game Using Flutter and Back4app
15 min
introduction in this tutorial, we’ll walk through how to build a sustainable game using flutter and back4app this game will educate users on eco friendly behaviors and reward them for taking positive actions for the environment we'll leverage back4app for backend services, such as tracking users' progress and rewarding them with digital items game concept ecowarrior the game will be called ecowarrior , where users take on small environmental tasks like recycling, saving water, and reducing energy consumption users will earn points and digital rewards as they complete tasks we'll focus on task logging and progress tracking users log the eco friendly actions they take reward system players earn points and badges for their contributions backend integration all user data and progress will be stored in back4app prerequisites flutter development setup follow the flutter installation guide https //flutter dev/docs/get started/install back4app account sign up for a free account at back4app https //www back4app com/ basic knowledge of flutter widgets and how to work with a backend step 1 set up back4app 1 1 create a back4app project log in to back4app https //www back4app com/ and create a new backend project called ecowarriorgame create a parse class called ecoactions with the following fields username (string) the username of the player actiontype (string) the type of action (e g , "recycling", "water conservation") points (number) the points awarded for the action timestamp (datetime) the time when the action was logged 1 2 set up your back4app credentials go to your back4app project’s settings and get your application id and client key these will be used to initialize back4app in flutter step 2 setting up your flutter project 2 1 create a new flutter project flutter create eco warrior cd eco warrior 2 2 add dependencies open pubspec yaml and add the following dependencies for parse sdk and flutter dependencies flutter sdk flutter parse server sdk flutter latest version provider ^5 0 0 # state management run flutter pub get to install the dependencies 2 3 initialize parse sdk in flutter in lib/main dart , initialize parse by adding your back4app credentials import 'package\ flutter/material dart'; import 'package\ parse server sdk flutter/parse server sdk flutter dart'; void main() async { widgetsflutterbinding ensureinitialized(); const keyapplicationid = 'your back4app app id'; const keyclientkey = 'your back4app client key'; const keyparseserverurl = 'https //parseapi back4app com'; await parse() initialize( keyapplicationid, keyparseserverurl, clientkey keyclientkey, autosendsessionid true, ); runapp(myapp()); } class myapp extends statelesswidget { @override widget build(buildcontext context) { return materialapp( title 'ecowarrior game', theme themedata(primaryswatch colors green), home gamescreen(), ); } } replace your back4app app id and your back4app client key with your actual back4app credentials step 3 game ui and functionality now we will build the ui of the ecowarrior game and integrate with back4app 3 1 create the gamescreen in lib/game screen dart , create a basic game interface where players can log environmental tasks and view their score import 'package\ flutter/material dart'; import 'package\ parse server sdk flutter/parse server sdk flutter dart'; class gamescreen extends statefulwidget { @override gamescreenstate createstate() => gamescreenstate(); } class gamescreenstate extends state\<gamescreen> { string? selectedaction; int score = 0; final list\<string> actions = \['recycling', 'water conservation', 'energy saving']; future\<void> logaction() async { if ( selectedaction == null) { scaffoldmessenger of(context) showsnackbar(snackbar( content text('please select an action '), )); return; } // assign points for the action int points = 0; switch ( selectedaction) { case 'recycling' points = 10; break; case 'water conservation' points = 15; break; case 'energy saving' points = 20; break; } // save action to back4app final ecoaction = parseobject('ecoactions') set('username', 'player1') // example username set('actiontype', selectedaction) set('points', points) set('timestamp', datetime now()); final response = await ecoaction save(); if (response success) { setstate(() { score += points; }); scaffoldmessenger of(context) showsnackbar(snackbar( content text('action logged! you earned $points points '), )); } else { scaffoldmessenger of(context) showsnackbar(snackbar( content text('failed to log action '), )); } } @override widget build(buildcontext context) { return scaffold( appbar appbar( title text('ecowarrior'), ), body padding( padding const edgeinsets all(16 0), child column( crossaxisalignment crossaxisalignment stretch, children \[ text( 'select an eco friendly action ', style textstyle(fontsize 18), ), dropdownbutton\<string>( value selectedaction, hint text('choose action'), items actions map((string action) { return dropdownmenuitem\<string>( value action, child text(action), ); }) tolist(), onchanged (string? newvalue) { setstate(() { selectedaction = newvalue; }); }, ), sizedbox(height 20), elevatedbutton( onpressed logaction, child text('log action'), ), sizedbox(height 20), text( 'current score $ score', style textstyle(fontsize 20, fontweight fontweight bold), ), ], ), ), ); } } step 4 retrieving user data from back4app we will retrieve and display the total score and actions the user has logged 4 1 fetch player’s score from backend to get the player’s score, we need to fetch all their actions from back4app and calculate the total score in lib/game screen dart , update gamescreenstate to include the fetching logic future\<void> fetchscore() async { final query = querybuilder\<parseobject>(parseobject('ecoactions')) whereequalto('username', 'player1'); // example username final response = await query query(); if (response success && response results != null) { int totalscore = 0; for (var result in response results!) { totalscore += result get\<int>('points')!; } setstate(() { score = totalscore; }); } } call fetchscore() when the screen is initialized @override void initstate() { super initstate(); fetchscore(); } step 5 running the game run the app on your device or emulator the player will select an action from the dropdown, log it, and their points will be saved to back4app the total score will be fetched from back4app and displayed on the screen step 6 expanding the game you can expand the ecowarrior game by adding more environmental tasks and actions implementing a leaderboard to show the top eco friendly players adding achievements for completing a certain number of tasks conclusion in this tutorial, we built a sustainable game using flutter and back4app the game allows players to log eco friendly actions, tracks their progress using a backend, and rewards them with points with flutter’s rich ui framework and back4app’s scalable backend, you can easily extend this concept to build more complex and interactive sustainable games for more information flutter documentation https //flutter dev/docs back4app documentation https //www back4app com/docs