Flutter / Dart-从MySQL服务器数据库下载数据 [英] Flutter/dart- download data from mysql server database

查看:100
本文介绍了Flutter / Dart-从MySQL服务器数据库下载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为此,我是所有事物的新手,不需要逐步的信息,只需看看有什么可能。

To preface this i am new to all of this and don't need step by step information, just seeing what is possible.

我一直在玩弄将flutter / dart应用程序连接到mysql后端

I've been toying around with connecting my flutter/dart app to a mysql backend

我使用sqljocky连接到它,并且想知道是否有用户可以从中下载数据以供离线使用。我了解了NSUserDefaults(适用于ios)和Shared_Preferences(适用于android),用于在应用程序上存储持久性和简单数据,并想知道这是否是继续进行下去的正确途径。

Im connecting to it using sqljocky and was wondering if there is anyway users can download data from it for offline use. I read about NSUserDefaults (for ios) and Shared_Preferences (for android) for storage of persistent and simple data on the app and wanted to know if this is the correct route to continue on.

推荐答案

我认为这里需要这个答案:

I think this answer is required here:

几天前,我不得不处理现有的MySQL数据库,除了通过网络请求外,无法使用Dart进行此操作(有一个与Dart 2不兼容的sqljocky程序包)。在此处阅读最佳选项。

Few days ago I had to dealt with a existing MySQL database and there was no way to do it with Dart except over network requests(there is a sqljocky package which is Dart 2 incompatible). Read best options here.

在这里,我将展示一个使用Flutter http请求和简单PHP& MySQL。

Here Im going to show an example for a simple fetch data using Flutter http request with simple PHP & MySQL.

注意:这可能不是100%安全的。

Note: This is may not 100% secure.

如果您在本地服务器中进行操作,您需要运行服务器(例如apache)和MySQL(您可以使用XAMPP来获得两者)。

If you are doing in local server, you need to have server(ex: apache) running and MySQL(you can use XAMPP to get both).


  • 步骤1 :创建数据库。

  • 步骤2:在htdocs(在XAMP中)中创建一个文件夹。接下来,在该文件内创建名为conn.php的文件。然后,在下面的代码段中添加并使用数据库凭据更改
    以连接到数据库。

  • Step 1: create a database.
  • Step 2: create a folder in htdocs(in XAMP). Next, inside that file create file called conn.php. Then, add below snippet and change with your db credentials to connect to database.

<?php

    $connection = new mysqli("localhost", "username", "password", "db_name");

    if (!$connection) {
        echo "connection failed!";
        exit();
    }
?>


注意:以上代码段是一个简单的示例,您可以根据需要进行自定义。

Note: above snippet is a simple example and you can customize as you want.


  • 步骤3:创建名为fetch_data.php的php文件,然后复制粘贴下面的代码段:

  • Step 3: Create php file called fetch_data.php and copy paste below code snippet:

<?php 

  include("conn.php");

  $queryResult = $connection->
      query("SELECT * FROM your_table");//change your_table with your database table that you want to fetch values

  $result = array();

  while ($fetchdata=$queryResult->fetch_assoc()) {
      $result[] = $fetchdata;
  }

  echo json_encode($result);
 ?>


以上代码段将从db中获取数据表并在 json_encode 之后显示。

Above code snippet will fetch the data from db table and display it after json_encode.

步骤4:打开Flutter项目或创建一个。下面是一个代码段,用于请求获取的数据并使用 ListView 显示它们。

Step 4: Open up your Flutter project or create one. Below is a code snippet that requesting for fetched data and display them using a ListView.

import 'dart:convert';

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(
      title: "Login",
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List data = [];

  @override
  void initState() {
    fetchData();
    super.initState();
  }

  void fetchData() async {
    final response = await http.get('http://10.0.2.2/fluttertest/fetch_data.php');

    if (response.statusCode == 200) {
      setState(() {
        data = json.decode(response.body);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: ListView.builder(
          itemCount: data.length,
          itemBuilder: (BuildContext context, int index) => ListTile(
                title: Text(data[index]['title']),
              )),
    );
  }
}

有一件重要的事情,请记住: 10.0.2.2 或您的计算机IP地址(在cmd中键入 ipconfig 来获取IP地址)必须使用,因为模拟器本身是localhost(127.0.0.1)。

There is an important thing, you should keep in mind: 10.0.2.2 or your machine IP address(type ipconfig in cmd to get your IP address) have to use because emulator itself localhost(127.0.0.1).

注意:我没有使用任何模型或高级工具来向您展示最低限度的示例。如果您想要一个很棒的CRUD示例,请检查我的github存储库,您还可以执行一些拉取请求,因为它可以

Note: I didn't use any model or advanced things to show you bare minimum example. If you want a great CRUD example, check my github repo and you can also do some pull requests because it's can extended.

如果要插入或更新数据,可以在PHP中使用 http.post()使用 INSERT UPDATE sql语句(最好使用Prepared Statement来防止sql注入)。

If you want to insert or update data, you can use http.post() and in php use INSERT, UPDATE sql statements(It's better using Prepared Statement to prevent sql injections).

您也可以阅读我的文章。在那里,我已经使用CRUD应用程序进行了解释。

Also you can read my article. There I have explained everything using a CRUD application.

这篇关于Flutter / Dart-从MySQL服务器数据库下载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆