Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

dart - How to connect flutter to localhost mysql database

I want to connect a localhost mysql db to flutter but I'm failing to do so. I tried mysql1 with these connections:

ConnectionSettings(
        host: '10.0.2.2',
        port: 3306,
        user: 'root',
        password: "root",
        db: 'company'

and i tried replacing host by 'localhost' and it didn't work. Any help? I am not using an emulator.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A connection directly to MySQL (or any other database access directly from clients) is not a good idea, except Firebase. If you want to interact with the MySql db a better solution is to create a server app and expose some HTTP REST API (with node.js, php ect.). With the API you can provide also a token for the client in order to access your data. You can make HTTP requests https://api.dartlang.org/stable/1.24.3/dart-io/HttpClient-class.html.

Now if for any reason you want still to connect directly to MySQL just keep in mind that any client application can access your DB with write permission in this case (and this is not a good practice at all!) just for a test example you can try creating a php file:

// Connect and insert data example

<?php 
    if (isset($_POST["value"])) {
        $servername = "localhost";
        $user = "username";
        $pw = "password";
        $db = "data";
        #Connect to Server
        $con = new Mysqli($servername, $user, $pw, $db) or die(Mysqli_errno());

        $value =htmlspecialchars(stripslashes(trim($_POST["value"])));

        $sql = $con->prepare("INSERT INTO tableName (value) VALUES ('$value')");
        $result = $sql->execute();
        if ($result) {
            echo "Success";
        }
        else {
            echo "Failed";
        }
        $con->close();
    } 
    else {
       echo "Not found";
    } 
?>

Also need to write the flutter part that make the request on http.post

void post() async {
    var result = await http.post(
        "http://{your url}/index.php",
         body: {
           "value": "Test DB Connection"
         }
    );
    print(result.body);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...