[flutter (플루터 앱 개발)] pHp backend with flutter

Hey guys on this article I am going to show you the step by step process that will enable you to connect your flutter app to a web server!

Learn — Unlearn — Relearn

Configure your web server

Let’s agree that the first step, to connect to a web server is to have a web server :D, well if you have your own server already, thats good

configure the webserver

Create MYSQL db ,create a database name, a username (for the database) and finally a password, make user you save this information because we are going to need it afterward

Now, after your database is created, go ahead and hit Manage -> phpmyadmin

3. now lets create a table on your database

Select the database you just created and then hit new to create a new table on your database

user the above attributes on the table that you are going to create, and finally insert some dummy values into the table, those values are the ones that we will retrieve from our flutter app.

After, you inserted the dummy data this is how the table will look like

Now let’s connect our app to our server

To do that we will need to create a file that is going to handle the connection with the server.page you will create two files, one called db.php and the other called get.php,

now select the file db.phpand edit its contents, the code will look like this:

<?php$dns = ‘mysql:host=localhost;dbname=enter-database-name’;
$user = ‘enter-username’;
$password = ‘enter_the_password_of_your_database’;try{
 $db = new PDO ($dns, $user, $pass);
}catch( PDOException $e){
 $error = $e->getMessage();
 echo $error;
}

Make sure to enter the correct credentials, or else you will get an error, from the home page, go to the manage databases window to get the correct credentials like database name and user name! $db = new PDO ($dns, $user, $pass); will create a PDO object and will establish the db connection, in case there is an error it will be thrown to the catch block

now select the get.php file, and edit its contents, the code is:

<?php
require_once('db.php');
$query = 'SELECT * FROM posts';
$stm = $db->prepare($query);
$stm->execute();
$row = $stm->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);

here we first require the db.php file, to establish connection with our databse, the we create a variable $query that is going to query our database table, then we use the PDO command $stm = $db->prepare($query) to make sure that our query is error free, and finally we user $stm->execute(); to execute the query, then $row = $stm->fetch(PDO::FETCH_ASSOC); will assign to the variable row the content of the table in the form of an associative array, echo json_encode($row); will display the response in the json format.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Now lets create our flutter app

we will create a simple flutter app with the following code

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';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 Server',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.pink,
      ),
      home: MyHomePage(title: 'Flutter Server App'),
    );
  }
}class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;  @override
  _MyHomePageState createState() => _MyHomePageState();
}class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        centerTitle: true,
      ),
    );
  }}

The above code will give you the basic app structure

Lets create the method to get the contents of our table on the server

Future getData() async{
    var url = 'https://serverurl/get.php';
    http.Response response = await http.get(url);
    var data = jsonDecode(response.body);
    print(data.toString());
  }

This code will get the content from our table and print it on the terminal, note that the method must be of type future and it must be asynchronous,

the url, that you have to provide on your code is your url/get.php

now we will call the method from the initial state

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

the complete code will look like this

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';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 Server',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.pink,
      ),
      home: MyHomePage(title: 'Flutter Server App'),
    );
  }
}class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;  @override
  _MyHomePageState createState() => _MyHomePageState();
}class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        centerTitle: true,
      ),
    );
  }  Future getData() async{
    var url = 'https://serverurl/get.php';
    http.Response response = await http.get(url);
    var data = jsonDecode(response.body);
    print(data.toString());
  }  @override
  void initState() {
    getData();
  }
}

Thank you for reading!

 

[출처] https://medium.com/gjam/php-backend-with-flutter-13e3f4b11e6c

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
151 [flutter (플루터 앱 개발)] flutter pocketbase 사용법 2탄(회원가입) file 졸리운_곰 2024.06.10 272
150 [flutter (플루터 앱 개발)] flutter pocketbase 사용방법 1탄(초기설정) file 졸리운_곰 2024.06.10 242
149 [게임 일반] 카드 덱 이미지 (트럼프 카드) 졸리운_곰 2024.05.27 224
148 [flutter (플루터 앱 개발)]Flutter - InAppWebview Communication (인앱웹뷰로 웹과 앱 양방향 통신하기, 자바스크립트 커뮤니케이션) file 졸리운_곰 2024.04.13 275
147 [flutter (플루터 앱 개발)] flutter - fvm 적용하기 (Futter Version Management) file 졸리운_곰 2024.04.11 189
146 [flutter (플루터 앱 개발)]Using Flutter FVM in Windows & MacOS file 졸리운_곰 2024.04.10 294
145 [flutter (플루터 앱 개발)] Flutter version management in Visual Studio Code with FVM 졸리운_곰 2024.04.10 231
» [flutter (플루터 앱 개발)] pHp backend with flutter file 졸리운_곰 2024.03.18 350
143 [flutter (플루터 앱 개발)] [Flutter] fvm으로 Flutter 버전 관리 졸리운_곰 2024.03.17 203
142 [firebase v9] 파이어베이스 버전9 시작하기 - firebase v9 file 졸리운_곰 2023.12.24 309
141 [ Firebase ] v9부터 크게 달라진 사용법들 모아보기 file 졸리운_곰 2023.12.24 268
140 [게임 개발 일반] 콘솔은 어려울수록, 모바일은 쉬울수록 '돈' 쓴다 file 졸리운_곰 2023.10.30 264
139 [Unity] How to Create a Metaverse dApp with Unity : Unity로 Metaverse dApp을 만드는 방법 file 졸리운_곰 2023.09.13 397
138 [게임 개발 일반] 게임 초기 기획서 작성 방법 졸리운_곰 2023.07.16 250
137 [GameMaker Studio] Neural Network in Game Maker Studio – part 4 file 졸리운_곰 2023.07.07 462
136 [GameMaker Studio] Neural Network in Game Maker Studio – part 3 file 졸리운_곰 2023.07.07 413
135 [GameMaker Studio] Neural Network in Game Maker Studio – part 2 file 졸리운_곰 2023.07.07 506
134 [GameMaker Studio] Neural Network in Game Maker Studio – part 1 file 졸리운_곰 2023.07.07 378
133 [construct2] HOW TO REMOVE THE SCREEN POWERED BY CONSTRUCT 2? file 졸리운_곰 2023.03.24 267
132 [flutter (플루터 앱 개발)] How to use Flutter’s Rest API file 졸리운_곰 2023.03.21 349
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED