Giter Site home page Giter Site logo

get_server's Introduction

Get Server

GetServer allows you to write backend applications with Flutter. Everything here is familiar, from the widgets, to the setState, initState and dispose methods, to the way you manage your projects with GetX using controllers and bindings. You don't need any additional knowledge to use GetServer, if you know Flutter, you can write your application's API using it. GetServer gives you 100% reuse of code between backend and frontend.

Flutter has become increasingly popular, and as it grows, there is also a new need for a niche of developers who want to use the same Stack. GetX for its ease and practicality has attracted many new developers every day, who started using Flutter to build mobile, desktop and also web applications. However, the GetX community has turned to a common need: the lack of a cohesive ecosystem for backend programming without a large learning curve. The purpose of this project is to supply the needs of these developers, who can now build backend applications with a 0% learning curve. If you already program in another language, I invite you to test it, if you feel good, or mastered another language, maybe GetServer is not for you, but we are happy to bring ease to people's lives, so if you program mobile but you have no idea how to create an api, you may have found what you were looking for. If you have a local database written in dart (like Hive and Sembast), you can turn it into a backend and build your api to provide them with a simple copy and paste. All of your Model classes are reused. All its route syntax is reused (if you use GetX) All of your business logic is reused.

Getting Started

Installing

Add Get to your pubspec.yaml file:

run dart create project and add to your pubspec:

dependencies:
  get_server:

Import get in files that it will be used:

import 'package:get_server/get_server.dart';

To create a server, and send a plain text:

void main() {
  runApp(
    GetServerApp(
      home: Home(),
    ),
  );
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text('Welcome to GetX!');
  }
}

However, if you don't need to have a single page, you will need named routes to define your urls. This is stupidly simple, and identical to GetX routes for frontend

void main() {
  runApp(GetServerApp(
    getPages: [
      GetPage(name: '/', page:()=> Home()),
    ],
  ));
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text("Welcome to GetX");
  }
}

you just define the path of your URL, and the page you want to deliver!

What if you want to return a json page?

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Json({
      "fruits": ["banana", "apple", "orange"]
    });
  }
}

Ok, you created your project with Flutter web, and you have no idea how to host it on a VPS, would it be possible to create the API for your application, and use the same GetX to display the Flutter web project? Yep. You need only copy your web folder from Flutter project, and paste on directory from server file. Flutter web generates an html file that calls a js file, which in turn requests several files that must be in a public folder. To make the Flutter web folder a public folder, just add it to your GetServer. That way when you enter your server, you will automatically be directed to site made with Flutter.

void main() {
  runApp(
    GetServerApp(
      home: FolderWidget('web'),
      getPages: [
        GetPage(name: '/api', page: () => ApiPage()),
      ],
    ),
  );
}
  • Note: Static folder only can be the root folder. It will replace any '/' route

If you have an html that does not call files from the server, but only external files, you can use the Html widget for a specific path.

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final path = '${Directory.current.path}/web/index.html';
    return Html(path);
  }
}

Ok, but what if I want to do a POST method to send a photo to my server, for example, how do I do this?

Okay, that sounds crazy, but you upload the file to your server, and retrieve it with an "upload.data". For the example not to be small, I will return a json response with the name of the file, his mimeType, and the same file back decoded in base64 so the example doesn't have just 5 lines.

class Home extends GetView {
  @override
  Widget build(BuildContext context) {
    return MultiPartWidget(
      builder: (context, upload) {
        return Json({
           "nameFile": upload.name,
           "mimeType": upload.mimeType,
           "fileBase64": "${base64Encode(upload.data)}",
        });
      },
    );
  }
}

How about Authentication? We have this as well.

First define a secret for your JWT:

void main() {
  runApp(
   GetServerApp(
    jwtKey: 'your key here',
   ),
  );
}

Second, retrieve your token:

final claimSet = JwtClaim(
  expiry: DateTime.now().add(Duration(days: 3)),
  issuer: 'get is awesome',
  issuedAt: DateTime.now(),
);

var token = TokenUtil.generateToken(claim: claimSet);

and finally just flag your routes that need the token to work:

GetPage(
  name: '/awesome-route',
  method: Method.get,
  page: () => YourPage(),
  needAuth: true,
),

I'm still not convinced, this is just an http server, but what if I want to create a chat that has real-time communication, how would I do that?

Okay, today is your lucky day. This is not just an http server, but also a websocket server.

class SocketPage extends GetView {
  @override
  Widget build(BuildContext context) {
     return Socket(builder: (socket) {
      socket.onOpen((ws) {
        ws.send('socket ${ws.id} connected');
      });

      socket.on('join', (val) {
        final join = socket.join(val);
        if (join) {
          socket.sendToRoom(val, 'socket: ${socket.hashCode} join to room');
        }
      });
      socket.onMessage((data) {
        print('data: $data');
        socket.send(data);
      });

      socket.onClose((close) {
        print('socket has closed. Reason: ${close.message}');
      });
    });
  }
}

Dart is not popular for servers, however, attracting people who already program in Flutter to the backend is now also a mission of GetX. Transforming one-dimensional programmers into full stack developers with 0% learning curve, and reusing code is also one of GetX's goals, and I hope you will help us on this journey.

The CI with Get Server is easy, you can write a file with the content above and put in .github/workflows/main.yml and then you will have as artifacts, your server's binary compilation for linux/windows/mac with each merge.

name: CI Building native server

on:
  # Triggers the workflow on push or pull request events but only for the main branch
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

jobs:
  build:
    runs-on: ${{ matrix.os }}

    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macOS-latest]
        include:
          - os: ubuntu-latest
            output-name: server-linux
          - os: macOS-latest
            output-name: server-mac
          - os: windows-latest
            output-name: server-windows.exe
    steps:
          - uses: actions/checkout@v2
          - uses: dart-lang/[email protected]
          - name: Install dependencies
            run: dart pub get
          - run: mkdir build
          - name: Install Dependencies
            run: dart pub get
          - run: dart compile exe ./lib/main.dart -v -o build/${{ matrix.output-name }}
          - uses: actions/upload-artifact@v1
            with:
                name: native-executables
                path: build

Like most of the "node.js" way?

The purpose of this package is to make development for Flutter developers easier. However, the javascript ecosystem is very large and you may be used to a more functional syntax. With get_server you can use this path. You can use get_server as well:

import 'package:get_server/get_server.dart';
void main() {
  final app = GetServer();
  app.get('/', (ctx) => Text('Get_server of javascript way'));
  app.ws('/socket', (ws) {
    ws.onMessage((data) {
      print('data: $data');
    });

    ws.onOpen((ws) {
      print('new socket opened');
    });

    ws.onClose((ws) {
      print('socket has been closed');
    });
  });
}

More Power

If you host your Getserver on a cheap server with few cores, the default option is more than enough. However, if you have a server with many cores and want to make the most of it, you can start the multithreaded server with isolates. This requires only a small step. Create a global function (isolated requirement), insert your runApp into it, and start it in runIsolate.

void main() {
  runIsolate(init);
}

void init(_) {
  runApp(
    GetServerApp(
      home: Home(),
    ),
  );
}

Note: This is a function that creates a thread for each CPU and you can use it throughout your application with GetServer. If you need activity with intense CPU and memory activity, you can use runIsolate.

How can you help?

  • Creating Pull requests, adding resources, improving documentation, creating sample applications, producing articles, videos about Getx, suggesting improvements, and helping to disseminate this framework in development communities.
  • Supporting this project.

TODO:

  • Add Auth options
  • Remove requirements dart:mirrors to allow people to compile the server and use only the binary, protecting its source code.
  • Creation of Bindings and Controllers (as in the main GetX) to adapt the project 100% with Getx for frontend.
  • Add some ORM

Accessing GetX:

GetX starts by default on port 8080. This was done to, if you want to install a reverse proxy like nginx, do it without much effort.

You could, for example, access the home page created in this example, using:

http://localhost:8080/ or http://127.0.0.1:8080/

However, if you want to start it on another port, such as 80, for example, you can simply do:

void main() {
  runApp(GetServer(
    port: 80,
    getPages: [
      GetPage(name: '/', page:()=> Home()),
    ],
  ));
}

To SSL you have too the certificateChain, privateKey, and password, configurations on GetServer

get_server's People

Contributors

cpdncristiano avatar dawidd6 avatar ductranit avatar idootop avatar jonataslaw avatar kabyeon avatar katekko avatar odunboye avatar seal1978 avatar unacorbatanegra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

get_server's Issues

How can i see logcat

I cannot found any log from terminal? How can i see the log print from GetServer

Read jwt token

How I can read jwt token after successfully authenticated? For example: In my token I put user Id in JWT payload and I should read this userId to get only userId data.

When running getserver, the server can't connect to mongodb?

When running getserver, the server can't connect to mongodb?

use mongo_dart: ^0.7.0+2

error: Error: Not found: 'dart:ui'

lib/main.dart: Warning: Interpreting this as package URI, 'package:mon_server/main.dart'.
../../flutter/packages/flutter/lib/src/foundation/basic_types.dart:9:1: Error: Not found: 'dart:ui'
export 'dart:ui' show VoidCallback;
^
../../flutter/packages/flutter/lib/src/foundation/binding.dart:8:8: Error: Not found: 'dart:ui'
import 'dart:ui' as ui show SingletonFlutterWindow, Brightness, PlatformDispatcher, window;
^
../../flutter/packages/flutter/lib/src/foundation/debug.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' as ui show Brightness;
^
../../flutter/packages/flutter/lib/src/foundation/key.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show hashValues;
^
../../flutter/packages/flutter/lib/src/foundation/stack_frame.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show hashValues;
^
../../flutter/packages/flutter/lib/src/foundation/binding.dart:100:3: Error: Type 'ui.SingletonFlutterWindow' not found.
ui.SingletonFlutterWindow get window => ui.window;
^^^^^^^^^^^^^^^^^^^^^^^^^
../../flutter/packages/flutter/lib/src/foundation/binding.dart:121:3: Error: Type 'ui.PlatformDispatcher' not found.
ui.PlatformDispatcher get platformDispatcher => ui.PlatformDispatcher.instance;
^^^^^^^^^^^^^^^^^^^^^
../../flutter/packages/flutter/lib/src/foundation/change_notifier.dart:68:20: Error: Type 'VoidCallback' not found.
void addListener(VoidCallback listener);
^^^^^^^^^^^^
../../flutter/packages/flutter/lib/src/foundation/change_notifier.dart:72:23: Error: Type 'VoidCallback' not found.
void removeListener(VoidCallback listener);
^^^^^^^^^^^^
../../flutter/packages/flutter/lib/src/foundation/change_notifier.dart:106:8: Error: Type 'VoidCallback' not found.
List<VoidCallback?> _listeners = List<VoidCallback?>.filled(0, null);
^^^^^^^^^^^^

jwt problem

hi,
thanks for your wonderfull package. I opened example, main page works well. But fruits page doesnt, because of needs auth. So i tryed to open 'localhost:8080/auth' page with post method for take a jwt. But it gives an error like this:

Unhandled exception: "String" not found. You need to call "Get.put(String())" or "Get.lazyPut(()=>String())" #0 GetInstance.find (package:get_server/src/framework/get_instance/src/get_instance.dart:332:7) #1 Inst.find (package:get_server/src/framework/get_instance/src/extension_instance.dart:70:45) #2 TokenUtil.getJwtKey (package:get_server/src/core/src/utils/token_util.dart:24:19) #3 TokenUtil.generateToken (package:get_server/src/core/src/utils/token_util.dart:6:17) #4 AuthController.getToken (package:buyboxserver/pages/auth/controller/view_controller.dart:13:22) #5 AuthPage.build (package:buyboxserver/pages/auth/view/auth.dart:8:28) #6 StatelessElement.build (package:get_server/src/core/src/widgets/widget.dart:165:28) #7 StatelessElement.performRebuild (package:get_server/src/core/src/widgets/widget.dart:158:5) #8 new StatelessElement (package:get_server/src/core/src/widgets/widget.dart:153:5) #9 StatelessWidget.createElement (package:get_server/src/core/src/widgets/widget.dart:139:12) #10 Route._sendResponse (package:get_server/src/routes/route.dart:99:15) #11 Route.handle.<anonymous closure> (package:get_server/src/routes/route.dart:86:11) #12 Route._verifyAuth (package:get_server/src/routes/route.dart:150:22) #13 Route.handle (package:get_server/src/routes/route.dart:77:5) #14 GetServerController.startServer.<anonymous closure> (package:get_server/src/core/src/server_main_controller.dart:95:17) #15 _RootZone.runUnaryGuarded (dart:async/zone.dart:1546:10) #16 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11) #17 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7) #18 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:733:19) #19 _StreamController._add (dart:async/stream_controller.dart:607:7) #20 _StreamController.add (dart:async/stream_controller.dart:554:5) #21 _HttpServer._handleRequest (dart:_http/http_impl.dart:3209:19) #22 new _HttpConnection.<anonymous closure> (dart:_http/http_impl.dart:2964:19) #23 _RootZone.runUnaryGuarded (dart:async/zone.dart:1546:10) #24 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11) #25 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7) #26 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:733:19) #27 _StreamController._add (dart:async/stream_controller.dart:607:7) #28 _StreamController.add (dart:async/stream_controller.dart:554:5) #29 _HttpParser._headersEnd (dart:_http/http_parser.dart:394:19) #30 _HttpParser._doParse (dart:_http/http_parser.dart:750:15) #31 _HttpParser._parse (dart:_http/http_parser.dart:324:7) #32 _HttpParser._onData (dart:_http/http_parser.dart:878:5) #33 _RootZone.runUnaryGuarded (dart:async/zone.dart:1546:10) #34 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11) #35 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7) #36 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:733:19) #37 _StreamController._add (dart:async/stream_controller.dart:607:7) #38 _StreamController.add (dart:async/stream_controller.dart:554:5) #39 _Socket._onData (dart:io-patch/socket_patch.dart:2160:41) #40 _RootZone.runUnaryGuarded (dart:async/zone.dart:1546:10) #41 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11) #42 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7) #43 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:733:19) #44 _StreamController._add (dart:async/stream_controller.dart:607:7) #45 _StreamController.add (dart:async/stream_controller.dart:554:5) #46 new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1696:33) #47 _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1208:14) #48 _microtaskLoop (dart:async/schedule_microtask.dart:40:21) #49 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5) #50 _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:120:13) #51 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:185:5) Macs-MacBook-Pro:buyboxserver macpro$ dart run lib/main.dart

So how can i use auth, i guess the 'localhost:8080/auth' page should give a jwt to me or im wrong. Please tell me more about how to use jwt on get_server package. Your document doesnt look enough for it.

useLog not working

GREAT work with get_server, it's an amazing package! ❤️
I know the flag for useLog is true by default, but it is no logging (tested in GET, POST - Multicores handler)
i am using: get_server: ^0.91.0
image

Unsupported operation: ServerSocket.bind

Hello

When starting a new Flutter web project and using the the example Code of the get_server readme.md:

import 'package:get_server/get_server.dart';

void main() {
  runApp(GetServer(
    public: Public('web'),
    getPages: [
      GetPage(name: '/', page: () => Home()),
    ],
  ));
}

class Home extends GetView {
  @override
  Widget build(BuildContext context) {
    return Text("Welcome to GetX");
  }
}

I get the following error:

Error: Unsupported operation: ServerSocket.bind at Object.throw_ [as throw] (http://localhost:51136/dart_sdk.js:4328:11) at Function._bind (http://localhost:51136/dart_sdk.js:57652:17) at Function.bind (http://localhost:51136/dart_sdk.js:57640:32) at Function.bind (http://localhost:51136/dart_sdk.js:182778:30) at Function.bind (http://localhost:51136/dart_sdk.js:176117:32) at server_main.GetServer.new.start (http://localhost:51136/packages/get_server/src/widgets/pageable.dart.lib.js:1141:31) at Object.runApp (http://localhost:51136/packages/get_server/src/widgets/pageable.dart.lib.

Any idea how to fix this?

Best regards
Marc

How can I use it in a normal flutter app?

For example, if I have the following codes:

Future<void> main(List<String> args) async {
  WidgetsFlutterBinding.ensureInitialized();

  // if I put it here, the UI won't start, I guess
  /*
  runApp(GetServer(
    getPages: [
      GetPage(name: '/', page:()=> Home()),
    ],
  ));
  */

  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (context) => AppModel()),
    ],
    child: MaterialApp(
      title: TITLE,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyApp(),
    ),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

How can I run the server in the background while still have the UI working properly?

Flutter web not Rendering

import 'dart:io';
import 'package:get_server/get_server.dart';

void main() {
runApp(
GetServer(
port: 21023,
// host: '127.0.0.1',
home: Home(),
),
);
}

class Home extends StatelessWidget {
@OverRide
Widget build(BuildContext context) {
return Html(path: '${Directory.current.path}/web/index.html');
}
}

Screenshot_1

upload file and got cast error

Upload file to server and got cast error in file widget.dart @jonataslaw

Error is
_CastError (type 'Future<Map<dynamic, dynamic>?>' is not a subtype of type 'FutureOr<Map<dynamic, dynamic>>' in type cast)

Function is

@override
  Future<MultipartUpload> file(String name, {Encoding encoder = utf8}) async {
    final payload = await (request.payload(encoder: encoder)
        as FutureOr<Map<dynamic, dynamic>>);
    final multiPart = await payload[name];
    if (multiPart is MultipartUpload) {
      return multiPart;
    } else {
      Get.log('Incorrect format, upload the file as Multipart/formdata',
          isError: true);
      return MultipartUpload(null, null, null, null);
    }
  }

Maybe we should wrap function's body with try..catch as below.

 @override
  Future<MultipartUpload> file(String name, {Encoding encoder = utf8}) async {
    try {
      final payload = await (request.payload(encoder: encoder)
          as FutureOr<Map<dynamic, dynamic>?>);

      final multiPart = await payload![name];
      if (multiPart is MultipartUpload) {
        return multiPart;
      } else {
        Get.log('Incorrect format, upload the file as Multipart/formdata',
            isError: true);
        return MultipartUpload(null, null, null, null);
      }
    } catch (e) {
      return MultipartUpload(null, null, null, null);
    }
  }

// I love get_server,It's Great!

Great start to great project

I like the idea, might take a few years to reach functionality of: https://fastapi.tiangolo.com
Look forward to hearing when it has a lot of the Fastapi features and a web interface to it to check it out!
Will definitely need at least CORS support and a good structure first!

Deploy server.js in node.js failed

Code in server.dart is:

import 'dart:math';
import 'package:get_server/get_server.dart';
void main() {
  final app = GetServer();
  var random = Random();
  app.get('/', (ctx) => Text('Get_server of javascript way-${random.nextInt(100)}'));
}

run it:

> dart bin/server.dart

It runs success and can response request.

Got server.js by command :

> dart compile js -o server.js bin/server.dart

Run server.js :

> node server.js

It will exited with code 0 and can not response request.

> dart --version
Dart SDK version: 2.14.3 (stable) (Wed Sep 29 13:10:26 2021 +0200) on "macos_x64"

Does server.js can deployed in nodejs ? and how.

Redis support for isolates instances

Using the isolate method to handle more requests with all CPU si a very good solution when we require to handle many user. This is a problem when we use the WebSocket, because as we know the websocket server need that all client must be connected to the same socket to dispatch messages to other clients.
Let's think about when we need to send a message to all connected clients or in a room. With a single server instance all work fine but if we isolate each instance to run with multiple CPUs this does not work.

Until now I have used NestJS as a backend for my applications, where there is an Adapter that solves just this problem using Redis.

Do you have planned a solution for that?

page not found in Android Simulator Fluttter APP with static folder

Hi, I try to run the get_server in a flutter app on Android Simulator,
I can return a Text('Hello') , but when I set a static folder, the page not found.
home: FolderWidget('web') // not found the folder

runApp(GetServer(
host: '0.0.0.0',
port: 8088,
home: FolderWidget('web', allowDirectoryListing:true),
getPages: [
GetPage(name: '/hello', page:()=>Text('Hello')),
],
));

Database Compatibility

Excellent, do you have in your roadmap incorporate compatibility to GraphQl or Connect to database driver such as Postgresql or mysql ?.
Again great idea about GetX Server.

Error

Brinks, só pra falar que o Jonny é foda mesmo.

How to get params from @Body

image
image
I'm test from Postman, method @post, and pass param as Body key-value (I don't want put param as segments in uri)
But server alway print null or empty like image. :(
Thanks

how to upload File(image,pdf, etc...) to server

I am currently using python fast api for backend , now i start learn Get server ,its best solution .now i stuck some functionality,
can you pls tell me how to upload files(images,pdf ...) to server folder using getx server...

async await response not work

I like the get_server package but here I'm facing problem with async and await during response.

import 'package:get_server/get_server.dart' as gs;

final app = gs.GetServer();

app.get('/users', (ctx) async{
   List users = await UserService.getUsers();
   return gs.Json(users);
})

How to call GetServer inside a flutter app?

What I want to achieve is to create a simple http server, hosted right from the app in a phone. which is something like this.

is there a way to do that?

Tried code below but I only get an error.

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get_server/get_server.dart' as server;

void main() {
  runApp(MaterialApp(
    home: HomePage(),
  ));
}

server.GetServer app;

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Container(
        child: MaterialButton(
          child: Text('Server Test'),
          onPressed: () {
            app = server.GetServer();
            app.get('/', () => server.Text('Hello World'));
            app.start();
          },
        ),
      ),
    );
  }
}

the error:

../../../.pub-cache/hosted/pub.dartlang.org/get_server-0.91.0/lib/src/infrastructure/get_instance/lifecycle.dart:46:4: Error: Getter not found: 'internal'.
  @internal
   ^^^^^^^^
../../../.pub-cache/hosted/pub.dartlang.org/get_server-0.91.0/lib/src/infrastructure/get_instance/lifecycle.dart:46:4: Error: This can't be used as metadata; metadata should be a reference to a compile-time constant variable, or a call to a constant constructor.
  @internal
   ^
../../../.pub-cache/hosted/pub.dartlang.org/get_server-0.91.0/lib/src/infrastructure/get_instance/lifecycle.dart:60:4: Error: Getter not found: 'internal'.
  @internal
   ^^^^^^^^
../../../.pub-cache/hosted/pub.dartlang.org/get_server-0.91.0/lib/src/infrastructure/get_instance/lifecycle.dart:60:4: Error: This can't be used as metadata; metadata should be a reference to a compile-time constant variable, or a call to a constant constructor.
  @internal
   ^

How to get help.

I'm new to this, to learn about servers I thought I'd have to learn another language, now I can do it with dart, but I have questions and I don't think I should open a new issue whenever I have one, how do I get help.

Get_Server Mysql connection query error

I have used to connect to mysql

when I try this code,

var settings = ConnectionSettings(
          host: 'localhost',
          port: 3306,
          user: 'root',
          password: '12345678',
          db: 'taxilv');
      var mySqlConnection = await MySqlConnection.connect(settings);
      var res = await mySqlConnection!.query('select name, email from users where id = ?', [1]);

I get this error when executing the query command

Unhandled exception:
RangeError (byteOffset): Invalid value: Not in inclusive range 0..5: 7
#0      _ByteDataView.getUint16 (dart:typed_data-patch/typed_data_patch.dart:4799)
#1      Buffer.readUint16 (package:mysql1/src/buffer.dart:240)
#2      new PrepareOkPacket (package:mysql1/src/prepared_statements/prepare_ok_packet.dart:20)
#3      Handler.checkResponse (package:mysql1/src/handlers/handler.dart:68)
#4      PrepareHandler.processResponse (package:mysql1/src/prepared_statements/prepare_handler.dart:45)
#5      ReqRespConnection._handleData (package:mysql1/src/single_connection.dart:349)
#6      ReqRespConnection._handleHeader (package:mysql1/src/single_connection.dart:318)
<asynchronous suspension>
#7      ReqRespConnection._readPacket (package:mysql1/src/single_connection.dart:303)
<asynchronous suspension>

How to set Cookie in websocket ?

Hi, I try to set cookie inside the websocket. But my code doesn't work.

socket.onOpen((ws) {
        context.response.cookie('name', 'hello');
        ws.send('hello');
});
socket.onMessage((message) {
        print (context.request.cookies); // []
});

Doc Example : Better chat.

Have been very interested in this but can't find any good examples out there in regards to the chat. I would love to see an example of how to create a simple chat application using a mobile device and get_server on my remote web server. I'm thinking that example could open the door for many applications such as designing a game service where people using ios and android can both communicate with the get_server backend to play poker, uno, etc.... An example for chat would be all I think a motivated programmer could use to open the possibilities.

Error on the "node.js way" example

Hi, I followed your example in the README.md, the "Like most of the node.js way" section, tried to run it like this (in main.dart):

import 'package:get_server/get_server.dart';

void main() {
  final app = GetServer();
  app.get('/', (ctx) => Text('Get_server of javascript way'));
  app.ws('/socket', (res) {
    res.ws.listen((socket) {
      socket.onMessage((data) {
        print('data: $data');
      });

      socket.onOpen((ws) {
        print('new socket opened');
      });

      socket.onClose((ws) {
        print('socket has been closed');
      });
    });
  });
}

And then, this error shows up:

Launching lib/main.dart on macOS in debug mode...
lib/main.dart:7:9: Error: The getter 'ws' isn't defined for the class 'BuildContext'.
 - 'BuildContext' is from 'package:get_server/src/core/server.dart' ('../../../../Apps/flutter/.pub-cache/hosted/pub.dartlang.org/get_server-1.1.0/lib/src/core/server.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'ws'.
    res.ws.listen((socket) {
        ^^
lib/main.dart:6:21: Error: A non-null value must be returned since the return type 'Widget' doesn't allow null.
 - 'Widget' is from 'package:get_server/src/core/server.dart' ('../../../../Apps/flutter/.pub-cache/hosted/pub.dartlang.org/get_server-1.1.0/lib/src/core/server.dart').
  app.ws('/socket', (res) {

It seems that the ws property isn't defined in the GetServer's BuildContext class. What I'm missing here? thanks.

Sometimes work, sometimes not.

The Get Server sometimes work , sometimes not.

1. main.dart

void main() {
runApp(GetServer(
getPages: [
GetPage(name: '/', page: () => Home()),
],
));
}

class Home extends GetView {
@OverRide
Widget build(BuildContext context) {
return Text("Welcome to GetX");
}
}

2. Run it.

Connecting to VM Service at ws://127.0.0.1:35359/VG1o4-TiZtg=/ws
lib/main.dart: Warning: Interpreting this as package URI, 'package:cool_server/main.dart'.
[GETX] Starting server on 127.0.0.1:8080 using 4 threads

3. Try it.

$ curl 127.0.0.1:8080
Welcome to GetX
$ curl 127.0.0.1:8080
$ curl 127.0.0.1:8080
$ curl 127.0.0.1:8080
$ curl 127.0.0.1:8080
$ curl 127.0.0.1:8080
$ curl 127.0.0.1:8080
Welcome to GetX
$ curl 127.0.0.1:8080

4. Look at the server.

[GETX] Method GET on /
[GETX] Method GET on /
[GETX] Method GET on /
[GETX] Method GET on /
[GETX] Method GET on /
[GETX] Method GET on /
[GETX] Method GET on /
[GETX] Method GET on /

SocketIO support

I'm very excited for this package, but in ma current server I use SocketIO and not simply Ws. Will we have any chance to have SocketIO support into this lib?

ORM for Get Server

Let me confess the fact that the GetX ecosystem is the most amazing thing that ever happened to Dart. With Fuchsia is on the horizon, it just feels right to have a unified full-stack Dart ecosystem. Get Server is the right step towards the backend of this unified full-stack ecosystem.
However, despite it's too early, but I think the GetX ecosystem as whole needs to have a formal roadmap.

One important part of the modern backend is ORM. Which is currently lacking in Get Server or probably in any other server-side Dart framework. Yes, I know that @jonataslaw already planning to have one. But the purpose of creating this issue is specific to give some opinion on the implementation of the upcoming ORM which I am expecting to be available sooner than later.

Here's my thought:
I have surfed enough of the backend frameworks from Laravel to Spring to Django to .NET for a while now. What I have found is that the ORMs on Django and .NET (Entity Framework) are two of the best there is. But in my observation, the Django ORM is tightly coupled to the Django framework. For example, you have to extend your model classes from models.Model class to ensure the ORM can detect changes. On the other hand, the .NET Entity Framework has something called Database Context. Which specifies all of the models that should be tracked. Models are simple classes without any extension.
Therefore, in my opinion, I think it would be nice to have an ORM like Entity Framework in Get Server (Or maybe in the Flutter front-end GetX too to be able to communicate with in-app databases like SQLite). We already have the amazing get_cli tool which can be used to generate the database migration classes/files without build_runner and also to sync/update the database (much like manage.py and dotnet-ef tool).

Also, can we have a GitHub organization now? As GetX is growing rapidly?

Thanks for the amazing work.

cannot return a json page as per example

Error

Unhandled exception:
NoSuchMethodError: Class '_InternalLinkedHashMap<String, String>' has no instance method 'toJson'.
Receiver: _LinkedHashMap len:1
Tried calling: toJson()

Hot reload?

Is there any possibility of support for hot reload.

WebSocket issue

Hi I try Get_Server and all work fine except for the websocket.
When I try to test websocket (for example with a Chrome extension) my server go down and raise an unhandled exception:

Unhandled exception:
WebSocketException: Invalid WebSocket upgrade request

Now if this is a protocol problem the should not terminate.

Does this package work on Flutter Web?

Hey. I am developing a Flutter web application and am trying to implement an HTTP server.
The dart:io library not working on Web
Is this library an exception?

How to Deploy Get_Server on VPS?

I am a fan of GetX and I wanna start to use Get_server for my backend side. Currently I use node.js I really wonder how can we deploy this framework on VPS?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.